Search code examples
phparraysxmlsimplexml

In_array not working


I have an array, I applied in_array function to find a specific number in that array, but it's showing no result, the data is inside the array but no response..:(

Array:

 Array
(
[0] => SimpleXMLElement Object
    (
        [0] => 572140
    )

[1] => SimpleXMLElement Object
    (
        [0] => 533167
    )

[2] => SimpleXMLElement Object
    (
        [0] => 572070
    )

[3] => SimpleXMLElement Object
    (
        [0] => 572383
    )

[4] => SimpleXMLElement Object
    (
        [0] => 285078
    )

[5] => SimpleXMLElement Object
    (
        [0] => 430634
    )
}

CODE I AM USING:

 if(in_array('285078',$arr))
    {
        echo 'yes';
    }
    else
    {
       echo "No";
    }

This is the array I am creating from the xml file..

 $arr = array();
 foreach($xmlInjury as $data)
 {
  array_push($arr,$data->player_id);
 }

It's only showing 'NO'.. please help me on this...


Solution

  • You need to cast them all first, then search. Like this:

    $new_arr = array_map(function($piece){
        return (string) $piece;
    }, $arr);
    
    // then use in array
    if(in_array('285078', $new_arr)) {
        echo 'exists';
    } else {
        echo 'does not exists';
    }