The Coding Blacklist. No 52: PHP array_search

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.

Got comments? Send me an email at fullstackdev@fullstackoasis.com. If you found this interesting, you can hit the subscribe button above. I write a new post about once a week.

1 thought on “The Coding Blacklist. No 52: PHP array_search

  1. Pingback: PHP in_array or array_search vs JavaScript includes or indexOf | Full Stack Oasis

Leave a Reply

Your email address will not be published. Required fields are marked *