PHP, empty arrays and conditionals
Published April 24th, 2008This is one of those silly little PHP quirks that catches me out from time to time, but apparently not often enough to avoid doing it again on occasion.
Let’s say you have a function (we’ll call it getSomeData())that returns an array, or false if there is a problem (yes you should probably be using exceptions, but let’s just say for argument’s sake that this is a third-party library over which you have no control). So you use a conditional to test whether the function had a problem or not:
// Try to get data
$data = getSomeData();
if( $data ){
//...do something
} else {
// There was a problem
error_log( "There was a problem getting data!" );
exit;
}
For the uninitiated the if() here calls the function and assigns its return value to $data. If the return value is any non-false value, the condition evaluates to true.
The quirk, if you want to call it that, is PHP’s understanding of what constitutes a ‘non-false’ value. You probably already know that null, 0 (zero) and ” (empty string) all evaluate to false. But the one that still catches me out now and then is that an empty array will evaluate to false, too. So in our above example, we’ll get an error if the getSomeData() function returns successfully, but with no data.
You could fix this with strict evaluation:
// Try to get data
$data = getSomeData()
if( $data === false ){
//...do something
} else {
// There was a problem
error_log( "There was a problem getting data!" );
exit;
}
…or alternatively (and better, in my opinion) check the return value’s type:
// Try to get data
$data = getSomeData();
if( is_array( $data ) ){
//...do something
} else {
// There was a problem
error_log( "There was a problem getting data!" );
exit;
}
If you want to know more, check out this blog post that goes into more detail — and points out a couple more unexpected ‘false’ values (the string ‘0′ and an object with no properties) that I wasn’t aware of.
Leave a comment
Comment Policy: First time comments are moderated. Please be patient.