PHP has a few “gotchas” which have bitten me in the past. I just got bitten again, today!
I used this PHP code:
$foods = Array();
$foods[] = 'ice cream';
$foods[] = 'hamburger';
$foods[] = 'brussels sprouts';
function do_important_things() {
echo 'Important!';
};
if (array_search('ice cream', $foods)) {
do_important_things();
}
I banged my head against the wall for a few minutes when the do_important_things
function never got called. I printed out the $foods
array and could see that 'ice cream'
was in it. So, array_search
should return true
, right?
So what was going on? Go figure it out for yourself if you want…. or scroll down to get the quick answer.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
PHP’s array_search
returns the key of the first value that was matched in the array. Since 'ice cream'
had key zero (first item in the array), 0
was returned. In PHP, 0
evaluates to FALSE
when it is used in a boolean sense. Like here. They kind of warn you about that in the array_search
documentation, but who looks up the docs every time they use an array function?
I kind of went ‘Doh!’ when this happened, because I’ve had this experience once before. I’d just forgotten it. This is a case where an editor plugin might help, but I don’t know of any good solution, except to be careful when using PHP array functions.
Pingback: PHP in_array or array_search vs JavaScript includes or indexOf | Full Stack Oasis