tags:

views:

122

answers:

5

I don't understand... I'm doing something and when I do print_r($var); it tells me that I have an array, so naturally I think I have an array yet when I do

if(is_array($xml->searchResult->item))

it returns false

I use this array with foreach(); in documentation it says that foreach() won't work with anything else but array, so assuming that this is an array that I'm working...

plus, if I try to access it via
echo $xml->searchResult->item[3];
i will get 4th element of my array

+3  A: 

well, is_array() returns true if your variable is an array, otherwise, it returns false. In your case, $xml->searchResult->item seems not to be an array. What is the output for

var_dump($xml->searchResult->item)

? Another hint: You can determine the type of a variable via gettype().

schneck
+6  A: 

print_r will also print objects as though they are arrays.

Will Shaver
This is exactly what is happening. XML nodes are objects.
Byron Whitlock
+1  A: 

is_array() returns true only for real php arrays. It is possible to create a "fake" array by using the ArrayAccess class. That is, you can use normal array semantics (such as item[3]) but it is not a real array. I suspect your $item is an object. So use

 if($x instanceof ArrayAccess || is_array($x))

Instead.

Martin Wickman
My understanding too. That the result of the OP's reference can be used as an array in a very few ways, but not only will `is_array()` not be true, but many of the standard array functions like `array_merge()` will not work with it.
grantwparks
A: 

The manual does mention that foreach works on objects as well, and it will iterate over properties.

In your case, the situation is slightly different because I guess you're using SimpleXML, which is yet another special case. SimpleXMLElement has its own iterator, which I assume is hardcoded as it doesn't seem to implement any of SPL's Iterator interfaces.

Long story short, some objects can be used as an array, but they are not one.

Josh Davis
A: 

plus, if I try to access it via echo $xml->searchResult->item[3]; i will get 4th element of my array

That's right, the first element is always 0 unless you specifically change it.

philm