Skip to content

Instantly share code, notes, and snippets.

Created April 16, 2021 18:51
What would you like to do?
This filters out a given number out from an array and returns the new length of the array
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));
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.

Copy link

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.

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.

Copy link

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