Check if an integer is in an array of object attributes

I have the following structure:

$foo_array = array(
  [0] => object(foo) {
    'id' => 1
  }
  [1] => object(foo) {
    'id' => 2
  }
)

And I want to check if int (1) exists in this id attribute of the array. How can i do this?

I was thinking of something like in_array(1, $foo_array), but of course, this does not work.

+4
source share
2 answers

This should work for you:

Just use array_reduce()for example

array_reduce($arr, function($keep, $v){
    if($v->id == 1)
        return $keep = TRUE;
    return $keep;
}, FALSE);
+1
source

You can do this using array_columnas (PHP> = 5.5)

in_array(1, array_column($foo_array,'id'))
+1
source

All Articles