Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Does if (count($array)) and if ($array) mean the same thing?

Tags:

arrays

php

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!

like image 965
alex Avatar asked Jun 05 '26 02:06

alex


1 Answers

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.

like image 82
gahooa Avatar answered Jun 06 '26 21:06

gahooa