On 06/02/13 15:18, Tyler Romeo wrote:
If you're checking for *whether an array is empty*, which is more intuitive:
if( !$array ) // If the boolean value of the array is false if( empty( $array ) ) // If the array is empty
The second is more intuitive. The first is more readable, since it doesn't look like an error made by someone who is unfamiliar with PHP, and who is thus following their intuition rather than their experience.
If you really want something that is readable by users who are unfamiliar with PHP, you can always use !count( $array ).
Functionally, they're almost equivalent, as any value that evaluates as false will also be treated as empty. The sole difference is 1) empty() first checks if the variable is set and 2) empty() is faster.
It doesn't seem faster to me.
$a = array('x'); $t = microtime(true); for ($i=0; $i < 10000000;
$i++ ) { empty($a); } print microtime(true) - $t; 0.57716178894043
$a = array('x'); $t = microtime(true); for ($i=0; $i < 10000000;
$i++ ) { !$a; } print microtime(true) - $t; 0.57688283920288
$a = array(); $t = microtime(true); for ($i=0; $i < 10000000; $i++ )
{ empty($a); } print microtime(true) - $t; 0.58778500556946
$a = array(); $t = microtime(true); for ($i=0; $i < 10000000; $i++ )
{ !$a; } print microtime(true) - $t; 0.57663702964783
The implementations are pretty much identical, so it's hard to see why one would be faster than the other.
I understand that there is a slight risk here due to empty()'s error suppression, but in many cases it's obvious that a variable exists and it's not necessary to sacrifice the logical readability of the code just because a developer might make a typo and not realize it even though the same variable is on the line above.
Developers often make typos without realising it, that's why we have the rule.
-- Tim Starling