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!
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!
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:
Since
then both cases illustrated in the question will always work as expected.
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
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.
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.