Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 666
DeDevelopers Avatar asked Sep 19 '14 09:09

DeDevelopers


2 Answers

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';
}
like image 193
Kevin Avatar answered Oct 04 '22 22:10

Kevin


First, your array is not array of strings, it's array of objects. If you can't change the structure of array try this:

foreach ($your_array as $item) {
    if (strval($item) == '25478') {
        echo 'found!';
        break;
    }
}

If you can change your array, add items to it like this:

$your_array[] = strval($appended_value);

After that you can use in_array.

like image 21
u_mulder Avatar answered Oct 04 '22 21:10

u_mulder