PHP is_array() and array_flip()

Error handling not only means placing try-catches whenever code can throw an exception. It also means capturing function return values, checking for empty or incorrect parameters, and (even in PHP) checking types.

array_flip() is a function that exchanges keys and values in an associative array. A good practice is to perform a is_array() check before to make sure we're going to operate with the correct type.

In a third party source code I found not long ago an array_flip() call, and surprisingly the code stopped working after I added the type check.

After some debugging, I found something curious: The code was generating an StdClass instead of an associative array (JSON decoding in PHP is weird "by default", but if you pass a true as the second parameter it will return the desired associative array); array_flip() worked with it in the past, but is_array() said (correctly) that it was not an array.

Why this happens?

According to the PHP documentation, array_flip() performs a cast to array of non-arrays. And not only that, the code after that call could operate with arrays because this function works by reference and the casting is performed on the parameter itself

Well, at least since PHP 5.3 this inconsistency has been fixed and array_flip() is strongly typed and will only accept true array parameters.

PHP has this old school habit of having a lot of functions that instead of returning the results operate with the parameters (as they are passed by reference). You have to get used to it whenever you like it or not.


Posted by Kartones on 2010-05-23