Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does is_array() return false?

I have this SimpleXML object:

object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}

Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?

Also, I am unable to cast it as an array using (array) $object->record. I get this error:

Warning: It is not yet possible to assign complex types to properties

like image 672
doremi Avatar asked Nov 30 '10 20:11

doremi


3 Answers

SimpleXML nodes are objects that can contain other SimpleXML nodes. Use iterator_to_array().

like image 122
bcosca Avatar answered Sep 18 '22 11:09

bcosca


It's not an array. The var_dump output is misleading. Consider:

<?php
$string = <<<XML
<?xml version='1.0'?>
<foo>
 <bar>a</bar>
 <bar>b</bar>
</foo>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
var_dump($xml->bar);
?>

Output:

object(SimpleXMLElement)#1 (1) {
  ["bar"]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
}

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(1) "a"
}

As you can see by the second var_dump, it is actually a SimpleXMLElement.

like image 30
Matthew Avatar answered Sep 21 '22 11:09

Matthew


I solved the problem using count() function:

if( count( $xml ) > 1 ) {
    // $xml is an array...
}
like image 27
AMIB Avatar answered Sep 19 '22 11:09

AMIB