Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP find Value in multidimensional Array [duplicate]

My Array looks like this:

$arr = Array();
$arr[] = Array("foo", "bar");
$arr[] = Array("test", "hello");

Now I want to check if $arrcontains an Array which contains foo on first position.

Is there any function for this or should I just loop $arr and search through every Array inside it?

like image 596
Tobias Baumeister Avatar asked Jun 14 '26 16:06

Tobias Baumeister


1 Answers

One nifty little way of doing this would be to use array_reduce – by passing in a function that sums up the values 1 if foo was found, and 0 if not:

$foo_found = array_reduce(
  $arr,
  function ($num_of_hits, $item, $search_for = 'foo') {
    $num_of_hits += $item[0] === $search_for ? 1 : 0;
    return $num_of_hits;
  }
);

$xyz_found = array_reduce(
  $arr,
  function ($num_of_hits, $item, $search_for = 'xyz') {
    $num_of_hits += $item[0] === $search_for ? 1 : 0;
    return $num_of_hits;
  }
);

var_dump($foo_found, $xyz_found);

returns 1 and 0, cause foo is found once, and xyz is found zero times.

like image 162
CBroe Avatar answered Jun 17 '26 06:06

CBroe