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.
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);