Search code examples
phparraysfunctional-programmingcallback

Change all values of an array without a loop construct


I have the following array in php:

$a = [0, 4, 5, 7];

I would like to increment all the values without writing a loop (for, foreach...)

// increment all values
// $a is now array(1, 5, 6, 8)

Is it possible in php?

And by extention, is it possible to call a function on each element and replace that element by the return value of the function?

For example:

$a = doubleValues($a); // array(0, 8, 10, 14)

Solution

  • This is a job for array_map() (which will loop internally):

    $a = array(0, 4, 5, 7);
    // PHP 5.3+ anonmymous function.
    $output = array_map(function($val) { return $val+1; }, $a);
    
    print_r($output);
    Array
    (
        [0] => 1
        [1] => 5
        [2] => 6
        [3] => 8
    )
    

    Edit by OP:

    function doubleValues($a) {
      return array_map(function($val) { return $val * 2; }, $a);
    }