PHP find Value in multidimensional Array -
this question has answer here:
- in_array() , multidimensional array 17 answers
my array looks this:
$arr = array(); $arr[] = array("foo", "bar"); $arr[] = array("test", "hello"); now want check if $arrcontains array contains foo on first position.
is there function or should loop $arr , search through every array inside it?
one nifty little way of doing use array_reduce – passing in function sums values 1 if foo found, , 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 , 0, cause foo found once, , xyz found 0 times.
Comments
Post a Comment