Search code examples
phparrayobject

How to search in array of std object (array of object) using in_array php function?


I have following std Object array

Array
(
    [0] => stdClass Object
        (
            [id] => 545
        )

    [1] => stdClass Object
        (
            [id] => 548
        )

    [2] => stdClass Object
        (
            [id] => 550
        )

    [3] => stdClass Object
        (
            [id] => 552
        )

    [4] => stdClass Object
        (
            [id] => 554
        )

)

I want to search for value of [id] key using loop. I have following condition to check whether value is exist or not like below

$flag = 1;
if(!in_array($value->id, ???)) {
    $flag = 0;
}

Where ??? I want to search in array of std Object's [id] key.

Can any one help me for this?


Solution

  • If the array isn't too big or the test needs to be performed multiple times, you can map the properties in your array:

    $ids = array_map(function($item) {
        return $item->id;
    }, $array);
    

    And then:

    if (!in_array($value->id, $ids)) { ... }