3

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!

0

4 Answers 4

3

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
)
Sign up to request clarification or add additional context in comments.

Comments

2

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
)

Comments

1

Not using array_map, it explicitly only maps values. But this'll do:

array_combine($a, array_map('cube', $a))

Comments

1

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
)

1 Comment

@Orangepill I misunderstood a key point in the poster's question. I thought array_map was returning an array with arbitrary keys but that is not the case. The other answers are more appropriate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.