This filters out a given number out from an array and returns the new length of the array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); |
Thanks for the review, I really appreciate.
However if I may ask,
- what do you mean by the term edge cases?
- 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.
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.
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
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 passednull
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.