Skip to content

Instantly share code, notes, and snippets.

@harmlessprince
Created April 16, 2021 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmlessprince/03bb86d4d73c584728c5ec55c56961ca to your computer and use it in GitHub Desktop.
Save harmlessprince/03bb86d4d73c584728c5ec55c56961ca to your computer and use it in GitHub Desktop.
This filters out a given number out from an array and returns the new length of the array
<?php
function filter_val( array $arr, int $val) : int{
$output = array_filter($arr, function($value) use ($val) {
return $value - $val != 0;
});
return count($output);
}
$array = [5,2,2,5,3];
$val = 5;
print_r(filter_val($array, $val));
@meekg33k
Copy link

Hello @harmlessprince, thank you for participating in Week 2 of Algorithm Fridays.

This is a decent solution; the only assumption your solution has made is that the input array cannot have a null value because what would happen if I passed null as the value of the $array on line 11? Ideally, you want to write code that is robust and doesn't fail on edge cases.

I've posted my solution here. Please read through and let me know what you think.

@harmlessprince
Copy link
Author

Thanks for the review, I really appreciate.
However if I may ask,

  1. what do you mean by the term edge cases?
  2. I intentionally type hinted the input so that, whoever tries to use the function will know what is expected with a well descriptive stack trace message that will be returned by the php compiler , I see no reason why the function should run at all, if the wrong input is given.

@meekg33k
Copy link

Edge cases basically are those unexpected cases that your program should still be able to handle. For example, invalid input, null input etc.
I agree with the type hinting for the input. but right now if I did this:

print_r(filter_val(NULL, 3));

Your code will not handle the NULL input gracefully.

@harmlessprince
Copy link
Author

Well, Understood, I guess the type hinting doesn't help the average user much...

Thanks for the review, Really appreciate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment