PHP: Can I get the index in an array_map function?

Ollie Glass picture Ollie Glass · May 3, 2011 · Viewed 56.9k times · Source

I'm using a map in php like so:

function func($v) {
    return $v * 2;
}

$values = array(4, 6, 3);
$mapped = array_map(func, $values);
var_dump($mapped);

Is it possible to get the index of the value in the function?

Also - if I'm writing code that needs the index, should I be using a for loop instead of a map?

Answer

Aron Rotteveel picture Aron Rotteveel · May 3, 2011

Sure you can, with the help of array_keys():

function func($v, $k)
{
    // key is now $k
    return $v * 2;
}

$values = array(4, 6, 3);
$mapped = array_map('func', $values, array_keys($values));
var_dump($mapped);