Daniel W.
Daniel W.

Reputation: 32290

SimpleXMLElement->array, in_array not working

print_r($xml);:

SimpleXMLElement Object
(
    [groupId] => Array
        (
            [0] => 1
            [1] => 5
        )
)

in_array(1, $xml->groupId) on this doesn't work: PHP Warning: in_array() expects parameter 2 to be array, object given

print_r((array)$xml->groupId); prints only first element in array:

Array
(
    [0] => 1
)

How can I properly check for an element existing in groupId, without a hack like json_decode(json_encode($xml->groupId)); ?

XML print_r($xml->asXML());:

<?xml version="1.0"?>
<return>
    <groupId>1</groupId>
    <groupId>5</groupId>
    <code>13</code>
</return>

Why does (array)$xml->groupId .... oh ... lol :-) Now I see the problem.... thanks

Upvotes: 0

Views: 491

Answers (1)

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

try

$xml = '<?xml version="1.0"?><return><groupId>1</groupId><groupId>5</groupId>
    <code>13</code></return>';

$xml = simplexml_load_string($xml);
print_r($xml);
if(in_array(1, (array)$xml)) {
    echo 'got it';
}else {
    echo 'not get';
}

Upvotes: 1

Related Questions