It's not mentioned on the documentation above, or in any of the notes, but if your anonymous function requires a variable from outside, you must use the "use" keyword, or it won't work.
Example 1:
<?php
$people = [
[
'id' => 23,
'name' => 'John',
'lastname' => 'Williams',
],
[
'id' => 56,
'name' => 'Hans',
'lastname' => 'Zimmer',
],
];
function filter_by_name ($name) {
global $people;
$filtered = array_filter($people, function($n) use($name) {
return $n['name'] == $name;
});
return $filtered;
}
print_r (filter_by_name ('John'));
?>
Example 2, with multiple variables:
<?php
$people = [
[
'id' => 23,
'name' => 'John',
'lastname' => 'Williams',
],
[
'id' => 56,
'name' => 'Hans',
'lastname' => 'Zimmer',
],
];
function filter_array_by_column ($array, $column, $value) {
$filtered = array_filter($array, function($row) use($column, $value) {
return $row[$column] == $value;
});
return $filtered;
}
print_r (filter_array_by_column ($people, 'name', 'John'));
?>