1

How to find the array which contains moo == 'gyu'?

$arr = [
  ['moo' => 'abc', 'foo' => 1], ['moo' => 'gyu', 'foo' => 2] ...
]

I know that should be answered already but unfortunately I wasn't able to find an example.

Thank you.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Bat Man
  • 369
  • 1
  • 4
  • 14

2 Answers2

4

Use array_filter() to to find target array. In callback function check value of moo index.

$newArr = array_filter($arr, function($item){
    return $item['moo'] == 'gyu';
});

Also you can use array_reduce() that return target array in result.

$newArr = array_reduce($arr, function($carry, $item){
    $item['moo'] == 'gyu' ? $carry = $item : "";
    return $carry;
 });

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
1

You have to used array_search() function for that.

if(array_search('gyu', array_column($arr, 'moo')) !== False) {
    echo "FOUND";
} else {
    echo "Not Found";
 }
Sandeep K.
  • 759
  • 6
  • 18