phparrayscallback

Difference between array_map, array_walk and array_filter


What exactly is the difference between array_map, array_walk and array_filter. What I could see from documentation is that you could pass a callback function to perform an action on the supplied array. But I don't seem to find any particular difference between them.

Do they perform the same thing?
Can they be used interchangeably?

I would appreciate your help with illustrative example if they are different at all.


Solution

  • Example:

    <pre>
    <?php
    
    $origarray1 = array(2.4, 2.6, 3.5);
    $origarray2 = array(2.4, 2.6, 3.5);
    
    print_r(array_map('floor', $origarray1)); // $origarray1 stays the same
    
    // changes $origarray2
    array_walk($origarray2, function (&$v, $k) { $v = floor($v); }); 
    print_r($origarray2);
    
    // this is a more proper use of array_walk
    array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; });
    
    // array_map accepts several arrays
    print_r(
        array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2)
    );
    
    // select only elements that are > 2.5
    print_r(
        array_filter($origarray1, function ($a) { return $a > 2.5; })
    );
    
    ?>
    </pre>
    

    Result:

    Array
    (
        [0] => 2
        [1] => 2
        [2] => 3
    )
    Array
    (
        [0] => 2
        [1] => 2
        [2] => 3
    )
    0 => 2.4
    1 => 2.6
    2 => 3.5
    Array
    (
        [0] => 4.8
        [1] => 5.2
        [2] => 10.5
    )
    Array
    (
        [1] => 2.6
        [2] => 3.5
    )