Reputation: 826
Iterating through an object... API response... for some strange reason, certain empty values are coming up as an empty array... i.e.
$foo->bar = array()
or
$foo->bar = array(0)
But when I try to check with:
if ( empty($foo->bar) )
Or even:
if ( is_array($foo->bar) )
It's not catching it. I've been converting the whole object to an array to get around this, which works, but is costing performance.
Is there something I'm missing here?
EDIT:
Going back, it looks like I mixed up my array with my object. What I NEED to check for is an empty value in a response such as:
[1] => SimpleXMLElement Object
(
[RecordID] => 14
[SomethingID] => 1
[SomethingName] => OKAY
[Integer] => 0
[String] => String
[AnotherInteger] => 1
[Empty] => SimpleXMLElement Object
(
)
[SomethingElseID] => 0
)
How do I check if $object->Empty is EMPTY?
EDIT:
var_dump shows:
object(SimpleXMLElement)#1343 (8) {
["RecordID"]=> string(2) "14"
["SomethingID"]=> string(1) "1"
["SomethingName"]=> string(4) "OKAY"
["Integer"]=> string(1) "0"
["String"]=> string(6) "String"
["AnotherInteger"]=> string(1) "1"
["Empty"]=> object(SimpleXMLElement)#1355 (0) { }
["SomethingElseID"]=> string(1) "0"
}
Upvotes: 1
Views: 237
Reputation: 2755
If your object uses the magical __get()
function to access an object's properties, an empty()
check will fail unless you are using PHP 5.5+.
From the docs:
Prior to PHP 5.5, empty() only supports variables; anything else will result in
a parse error. In other words, the following will not work: empty(trim($name)).
If you use the magical method to access the property, it is like doing empty($object->__get($property))
EDIT: Note that though the docs mention that it results in a parse error, I've never actually seen it result in a PHP error, I believe it simply returns false
Upvotes: 0
Reputation: 75629
Use empty($array)
(docs) to determine if you array is empty.
EDIT
Yes, I noticed OP stated he uses empty()
but you can always do something like:
function isArrayEmpty($arr) {
return (count($arr) == 0);
}
for verification purposes. empty()
is (theoretically) the way to go. And you can always use var_dump()
or print_r()
to inspect why empty()
claims array is not empty while you bet it should be.
Also @chameleon answer lead me to this: https://bugs.php.net/bug.php?id=24915 - if your class is using __get()
then using count()
instead of empty()
may be the workaround.
Upvotes: 2
Reputation: 1926
You can also use foreach
to determine if an array is empty, although I recommend @Marcin's method
foreach($array as $key => $value){
if(empty($value)){
unset($array[$key]);
}
}
Upvotes: 0