I execute code in PHP 5.3.3.

<?php $arr1 = array(); var_dump(empty($arr1)); $arr2; var_dump(empty($arr2)); $arr3 = array(0); var_dump(empty($arr3)); $arr4 = array(null); var_dump(empty($arr4)); $arr5 = array(false); var_dump(empty($arr5)); $arr6 = array(""); var_dump(empty($arr6)); $arr7 = array(" "); var_dump(empty($arr6)); ?> 

Result of performance

 bool(true) bool(true) bool(false) bool(false) bool(false) bool(false) bool(false) 

It does not match the documentation, which indicates that it returns FALSE if the var exists, and contains a non-empty and non-zero value. Otherwise, returns TRUE. the following values ​​are considered empty:

 "" (пустая строка) 0 (целое число) 0.0 (дробное число) "0" (строка) NULL FALSE array() (пустой массив) 

How can this be explained. Is the result different in PHP 3 compared to PHP 4 or 5?

  • In PHP7, I got exactly the same result. bool (true) bool (true) bool (false) bool (false) bool (false) bool (false) bool (false) - ilyaplot
  • well, but this result does not agree with what is written in the documentation (indicated above), or did I not understand it? - Beginner
  • no .. there is a question in discrepancy with the documentation or I did not understand the essence - Beginner

1 answer 1

For an array, empty will say true only if the array is empty. Those. if the array does not contain any elements.

Your $arr1 is empty, it does not contain any elements.

$arr2 does not exist at all.

All the following examples contain a non-empty array, there is one element in each. Which element is exactly - empty doesn't care at all. The array contains at least one element, it means it is not empty, it means false .

This is explicitly stated in the documentation: array() (пустой массив) . It is an empty array that is considered empty

  • but the documentation says that the following values ​​are perceived as empty: null, false, 0, "0". What did they mean by this? After all, they are not empty and return empty false. - Beginner
  • @Sven and what have the arrays? You do not confuse the emptiness of an array variable, and the emptiness of its elements. - teran
  • $var = null; var_dump(empty($var)); will be true. null is treated as an empty value. array( null ) - is an array. There is one element in the array. So this is not an empty array and empty will say false. In the data itself in the empty array will not get, it is not his concern. - Shallow
  • Thanks for this post .. understand now! - Beginner