note 126954 added to function.array-map
| From: | Walf at main dot php dot net | Date: | Thu, 24 Mar 2022 23:48:21 +0000 |
| Subject: | note 126954 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217764@lists.php.net to get a copy of this message | ||
A general solution for the problem of wanting to know the keys in the callback, and/or retain the
key association in the returned array:
<?php
/**
* Like array_map() but callback also gets passed the current key as the
* first argument like so:
* function($key, $val, ...$vals) { ... }
* ...and returned array always maintains key association, even if multiple
* array arguments are passed.
*/
function array_map_assoc(callable $callback, array $array, array ...$arrays) {
$keys = array_keys($array);
array_unshift($arrays, $keys, $array);
return array_combine($keys, array_map($callback, ...$arrays));
}
?>
Because it uses array_map() directly, it behaves the same way in regard to ignoring the keys of
subsequent array arguments. It also has the same variadic signature.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 60.231.232.99)
----
Manual Page -- https://php.net/manual/en/function.array-map.php
Edit -- https://main.php.net/note/edit/126954
Del: integrated -- https://main.php.net/note/delete/126954/integrated
Del: useless -- https://main.php.net/note/delete/126954/useless
Del: bad code -- https://main.php.net/note/delete/126954/bad+code
Del: spam -- https://main.php.net/note/delete/126954/spam
Del: non-english -- https://main.php.net/note/delete/126954/non-english
Del: in docs -- https://main.php.net/note/delete/126954/in+docs
Del: other reasons-- https://main.php.net/note/delete/126954
Reject -- https://main.php.net/note/reject/126954
Search -- https://main.php.net/manage/user-notes.php