tags:

views:

1590

answers:

4

Hi

In PHP, will these always return the same values?

//example 1

$array = array();

if ($array) {
   echo 'the array has items';

}

// example 2

$array = array();

if (count($array)) {
   echo 'the array has items';

}

Thank you!

+7  A: 

From http://www.php.net/manual/en/language.types.boolean.php, it says that an empty array is considered FALSE.


(Quoted): When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags


Since

  • a count() of > 0 IS NOT FALSE
  • a filled array IS NOT FALSE

then both cases illustrated in the question will always work as expected.

gahooa
Thank you mate! :)
alex
+1  A: 

Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element.

See also: http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Mike Boers
+1  A: 

Note that the second example (using count()) is significantly slower, by at least 50% on my system (over 10000 iterations). count() actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like empty(), and stops as soon as it finds at least one element.

James Socol
Thanks for that... I'm always looking to optimise my code!
alex
+3  A: 

Those will always return the same value, but I find

$array = array();

if (empty($array)) {
   echo 'the array is empty';
}

to be a lot more readable.

Bill the Lizard