note 129703 added to function.array-filter

From: Date: Mon, 12 Aug 2024 22:23:17 +0000
Subject: note 129703 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-221476@lists.php.net to get a copy of this message
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')); ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 190.191.124.210) ---- Manual Page -- https://php.net/manual/en/function.array-filter.php Edit -- https://main.php.net/note/edit/129703 Del: integrated -- https://main.php.net/note/delete/129703/integrated Del: useless -- https://main.php.net/note/delete/129703/useless Del: bad code -- https://main.php.net/note/delete/129703/bad+code Del: spam -- https://main.php.net/note/delete/129703/spam Del: non-english -- https://main.php.net/note/delete/129703/non-english Del: in docs -- https://main.php.net/note/delete/129703/in+docs Del: other reasons-- https://main.php.net/note/delete/129703 Reject -- https://main.php.net/note/reject/129703 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221476) next »