Reputation: 1030
I have an array like this:
[0] => Array(
[student_id] => 6
[gender] => 1
[student_name] => name1
)
[1] => Array(
[student_id] => 26
[gender] => 2
[student_name] => name2
)
[2] => Array(
[student_id] => 75
[gender] => 2
[student_name] => name3
)
[3] => Array(
[student_id] => 1
[gender] => 1
[student_name] => name4
)
[4] => Array(
[student_id] => 10
[gender] => 1
[student_name] => name5
)
I would like to list the student names or array keys where gender
is 2
.
What is the most efficient way to achieve this?
Avoiding foreach should be better.
Upvotes: 1
Views: 98
Reputation: 1031
Try this
function check_gender($element) {
return $element['gender'] === gender[2];
}
array_filter(check_gender, $the_array);
Upvotes: 0
Reputation: 68476
A simple foreach
would do..
$searchKey = 2;
foreach($yourarray as $k=>$arr)
{
if($arr['gender']==$searchKey)
{
echo $arr['student_name']."<br>";
}
}
array_map()
As you mentioned you are avoiding a foreach
. This function still uses internal loop structures which is hidden. You should probably use the foreach
instead as it is easily - readable.
$searchKey=2;
array_map(function($v) use($searchKey) { if($v['gender']==$searchKey){ echo $v['student_name']."<br>";}}, $yourarray);
Upvotes: 2
Reputation: 2429
For this sort of operation, it's generally a good idea to use a filter:
function check_gender($element) {
return $element['gender'] === 2;
}
array_filter(check_gender, $the_array);
Keep in mind that anonymous functions are only available from PHP 5.3 on. If you need your code to run on an older version of PHP, you'll need to declare the function first, like in the code above. If you're sure your code will only ever need to run on PHP 5.3 or newer, you can directly place an anonymous function as an argument of array_filter
.
Upvotes: 3
Reputation: 160833
You could use array_filter to filter the array.
$students = array_filter($students, function($var) {
return $var['gender'] === 2;
});
And if you want to collect the names as an array, there is array_map:
$names = array_map(function($var) {
return $var['student_name'];
}, $students);
Upvotes: 4
Reputation: 1490
Assuming the array is unsorted, the best you can do is a simple loop through the array and check each key. Since the array is unsorted, you'll need to check every gender field.
Upvotes: 1