Reputation: 1471
The empty() function in php 5.3 does not work well for associative arrays. I have an associative array that could have some 30+ elements.
$arr = array(
'one'=>kwara,
'two'=>osun,
...
'thirty'=>lagos
)
If the associative array is empty like so:
$arr = array(
'one'=>'',
'two'=>'',
...
'thirty'=>''
)
and I need to check if the array is empty, the following will not work in php 5.3.
if(empty($arr))
{
echo "array is empty<br />>";
}
else
{
echo "array is NOT empty<br />";
}
and will return 'array is NOT empty'. I am aware that the behaviour is different in php 5.4 but my current platform is php 5.3.
To overcome this problem, I have used the following:
if(strlen(implode('',array_values($arr))) > 0)
{
echo "array is NOT empty<br />>";
}
else
{
echo "array is empty<br />";
}
The question is: is there a better of achieving this in php 5.3?
Upvotes: 1
Views: 100
Reputation: 4248
Empty will work only with really empty values, your array has keys assigned so its not empty. Your solution is probably best way to do what you want - its hard to say, you would need to make some benchmarks, it can be done in many other ways:
if (array_filter($arr) === array()) {}
// or
if (!implode('', $arr)) {}
Upvotes: 0
Reputation: 41867
Short answer: No
Longer answer: The array you are looking at is not empty at all, it contains a bunch of keys with zero length strings. Your solution is probably one of the shortest possible and readable. You may want to wrap it in a function of your own though.
Upvotes: 2
Reputation: 46060
Have you tried:
if (sizeof(array_filter($array)) === 0) // do your stuff
Also you original could be improved like:
if (implode($array) !== '') // do your stuff
Upvotes: 2