note 120324 added to function.array-map
| From: | ET | Date: | Tue, 13 Dec 2016 16:21:55 +0000 |
| Subject: | note 120324 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-208581@lists.php.net to get a copy of this message | ||
If you need to map both the keys AND the values of an array (be it associative or not) you can use a
function like this:
<?php
function array_map_assoc($callback, $arr) {
$remapped = array();
foreach($arr as $k => $v)
$remapped += $callback($k, $v);
return $remapped;
}
?>
For example:
<?php
$arr = array(
'cat' => 'tom',
'mouse' => 'jerry'
);
$newArr = array_map_assoc(function($k, $v) {
return array(
'another_' . $k => $v . '\'s clone'
);
}, $arr);
print_r($newArr);
?>
The example above will output:
<?php
Array
(
[another_cat] => tom's clone
[another_mouse] => jerry's clone
)
?>
You can even use it with non associative arrays, for example to shift the indexes while changing the
values:
<?php
$arr = array(
0 => 'tom',
1 => 'jerry'
);
$newArr = array_map_assoc(function($k, $v) {
return array(
($k + 10) => $v . '\'s clone'
);
}, $arr);
print_r($newArr);
Array
(
[10] => tom's clone
[11] => jerry's clone
)
?>
----
Server IP: 31.14.131.242
Probable Submitter: 151.62.156.3
----
Manual Page -- http://php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/120324
Del: integrated -- https://master.php.net/note/delete/120324/integrated
Del: useless -- https://master.php.net/note/delete/120324/useless
Del: bad code -- https://master.php.net/note/delete/120324/bad+code
Del: spam -- https://master.php.net/note/delete/120324/spam
Del: non-english -- https://master.php.net/note/delete/120324/non-english
Del: in docs -- https://master.php.net/note/delete/120324/in+docs
Del: other reasons-- https://master.php.net/note/delete/120324
Reject -- https://master.php.net/note/reject/120324
Search -- https://master.php.net/manage/user-notes.php