Reputation: 33
Using the canonical PHPdoc example, this code:
<?php
function cube($n)
{
return($n * $n * $n);
}
$a = array( 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>
outputs
Array
(
[0] => 27
[1] => 64
[2] => 125
)
But what I really want it to output is something along these lines: Array
(
[3] => 27
[4] => 64
[5] => 125
)
That is, I want the array_map to use the same keys as in the original array. Is there any way to do that? Thanks!
Upvotes: 3
Views: 206
Reputation: 24645
While you can't use array_map to rewrite keys you can use array_reduce with a closure (PHP 5.3+)
<?php
function cube($n){
return $n*$n*$n;
}
$data = array(3,4,5);
$function = "cube";
$res = array_reduce($data, function(&$result = array(), $item) use($function){
if (!is_array($result)){
$result = array();
};
$result[$item] = $function($item);
return $result;
});
print_r($res);
The output is
Array
(
[3] => 27
[4] => 64
[5] => 125
)
Upvotes: 2
Reputation: 7999
Instead of using array_map
which returns a modified array you could use array_walk
which can modify the given array. Note that the callback used by array_walk
needs to accept its arguments by reference if you intend to change them
<?php
$cube = function(&$x) {
// Modify $x by reference
$x = pow($x, 3);
};
$data = array(
3 => 3,
4 => 4,
5 => 5
);
array_walk($data, $cube);
print_r($data);
This prints
Array
(
[3] => 27
[4] => 64
[5] => 125
)
Upvotes: 1
Reputation: 522085
Not using array_map
, it explicitly only maps values
. But this'll do:
array_combine($a, array_map('cube', $a))
Upvotes: 1
Reputation: 59699
Use array_combine()
:
$b = array_combine( $a, array_map("cube", $a));
You can see from this demo that it produces:
Array
(
[3] => 27
[4] => 64
[5] => 125
)
Upvotes: 3