The reasons that your check_value_old()
function breaks is because you have a typo in your loop's second parameter. $status_list
is not one of the variables passed into your function and it is not declared anywhere before it is used. You merely need to use $list
instead. It is also not necessary to call count()
on every iteration -- since that value never changes in the loop, just call it once before the loop and use that value in the second parameter.
As for deciding how to loop over array values, there is no reason to reinvent a native function call. in_array()
was already designed and optimized to search linear values in an array and return true
as soon as it finds a match; otherwise it returns false
.
I don't know what @AnthonyForloney is doing by writing in_array()
inside of a foreach()
loop. Not only will the snippet break because there aren't enough curly braces, the input array does not have two levels of data, so in_array()
will choke when it receives $current
which is a string (not the expected array).
Ultimately, my advice is: Only write your own custom function when there isn't a native function to suit your needs. Throw away both of the manual looping ideas and only call:
$arr = ["hello", "good bye", "ciao", "buenas dias", "bon jour"];
var_export(in_array("buenas dias", $arr));
One final insight that I'd like to provide is regarding microoptimization. If you are planning to check the existence of a unique value in a "very large" array, or if you are going to be making thousands of searches on the same array, then it would be more efficient to set up your array in a "flipped" orientation and call isset()
or array_key_exists()
. isset()
/array_key_exists()
will always outperform in_array()
or array_search()
because of the way that php handles arrays as "hash maps". More reading here.