Skip to content

Instantly share code, notes, and snippets.

@harmlessprince

harmlessprince/filterval.php Secret

Created Apr 16, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 19, 2021

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

This comment has been minimized.

Copy link
Owner Author

@harmlessprince harmlessprince commented Apr 20, 2021

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

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 24, 2021

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

This comment has been minimized.

Copy link
Owner Author

@harmlessprince harmlessprince commented Apr 24, 2021

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