This question already has an answer here:
My Array looks like this:
$arr = Array();
$arr[] = Array("foo", "bar");
$arr[] = Array("test", "hello");
Now I want to check if $arr
contains 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?
</div>
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.
Your Array:
$arr = Array();
$arr[] = Array("foo", "bar");
$arr[] = Array("foo", "hello");
My Solution:
echo search_in_array("foo",$arr); // This will show you the number of items found
function search_in_array($value, $arr){
$num = 0;
for ($i = 0; $i < count($arr); ) {
if($arr[$i][0] == $value) {
$num++;
}
$i++;
}
return $num ;
}
I think there are few different ways to do it. please check the following
$arr_zero = Array();
$arr_zero[] = Array("foo", "bar");
$arr_zero[] = Array("test", "hello");
$arr_zero[] = Array("nal", "rob");
$array_one = array_shift(array_values($arr_zero));
$element = array_shift(array_values($array_one));
if($element=='foo');
echo "its ok";
or
$arr_zero = Array();
$arr_zero[] = Array("foo", "bar");
$arr_zero[] = Array("test", "hello");
$array_one = array_shift(array_values($arr_zero));
$element = reset($array_one); // First Element's Value
if($element=='foo');
echo "its ok";
or
$arr_zero = Array();
$arr_zero[] = Array("foo", "bar");
$arr_one = $arr_zero[key($arr_zero)];
echo $arr_one[key($arr_one)];
To get key
$arr_zero = Array();
$arr_zero[] = Array("foo", "bar");
$arr_zero[] = Array("test", "hello");
$array_one = array_shift(array_values($arr_zero));
echo key($array_one); // First Element's Key