1

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?

2
  • @Phil, I checked a link which you have specified but I think solution which Jack has provided is far better. Commented Jan 22, 2014 at 5:47
  • It depends on the use-case, really. My answer requires more memory, for instance. Commented Jan 22, 2014 at 5:50

4 Answers 4

5

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)) { ... }
Sign up to request clarification or add additional context in comments.

2 Comments

That's great friend (y). I was looking for this since long time. Again thank you so much.
As I am able to accept your answer I will accept it and mark as solved.
1

try:

foreach ($array as $val) {
 if (!in_array($id, (array) $val)) {
 ...
 }
}

2 Comments

this answer is already given by another user.
hey this looks familiar..
0

Why not just cast the objects as arrays:

foreach ($array as $a) {
     if (!in_array($id, (array) $a)) {
     ...
     }
}

1 Comment

I don't know why people hate the easy ways ;)
0

Assuming your array is names $yourArray ,

$newArr = array();
foreach ($yourArray as $key=>$value) {
    $newArr[] = $value->id;
}

And now $newArr is like : array(545,548,550,552,554)

AND you can search in it by :

$valueOfSearch = ... ;
$flag = 1;
if(!in_array($valueOfSearch,$newArr)) {
    $flag = 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.