Title: PHP is_array() and array_flip()
Slug: php-is-array-and-array-flip
Date: 2010-05-23 14:20:00
Author: Kartones
Lang: en
Tags: Development, PHP, Troubleshooting
Description: The importance of error handling in PHP, and the need to check types.

 <p>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.</p> <p><a href="http://php.net/manual/en/function.array-flip.php">array_flip()</a> is a function that exchanges keys and values in an associative array. A good practice is to perform a <a href="http://php.net/manual/en/function.is-array.php">is_array()</a> check before to make sure we're going to operate with the correct type.</p> <p>In a third party source code I found not long ago an <font face="Courier New">array_flip()</font> call, and surprisingly the code stopped working after I added the type check.</p> <p>After some debugging, I found something curious: The code was generating an <font face="Courier New">StdClass</font> instead of an associative array (JSON decoding in PHP is weird "by default", but if you pass a <font face="Courier New">true</font> as the second parameter it will return the desired associative array); <font face="Courier New">array_flip()</font> worked with it in the past, but <font face="Courier New">is_array()</font> said (correctly) that it was not an array.</p> <p>Why this happens?</p> <p> </p> <p>According to the PHP documentation, <font face="Courier New">array_flip()</font> 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 *</p> <p> </p> <p>Well, at least <a href="https://prototype.php.net/versions/5.3/">since PHP 5.3</a> this inconsistency has been fixed and <font face="Courier New">array_flip()</font> is strongly typed and will only accept true array parameters.</p> <p> </p> <p>* 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.</p>
