0

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

6 Answers 6

6

print_r will also print objects as though they are arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what is happening. XML nodes are objects.
3

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().

Comments

1

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.

1 Comment

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.
1

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.

Comments

0

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.

Comments

0

Just be careful to check what has been returned by your array. You might have an object with class or stdClass which is empty and you cannot get element from it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.