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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With