Web Development & WordPress

When to Use array_walk() and array_map() in PHP: Working with Individual Array Elements

array_walk() and array_map() both are used to work with the individual array element. array_walk() allows for operations to be performed on each element, but it does not return a new array. Instead, it operates directly on the original array and is typically used for side effects like printing, modifying elements in-place, or other operations where the result is not needed in a new array.

On the other hand, array_map() Returns a new array with modified values.

<?php
$arrWalk = array(1, 3, 2, 4, 2, 1, 5, 6, 3, 4, 5);
echo "Original Array<br>";
echo "<pre>";
print_r($arrWalk);
echo "</pre>";

echo "<br>After Doubling the array elements:<br><br>";

function doubleit($n)
{
    echo "Double of {$n} is:" . $n * $n . "<br>";
}

array_walk($arrWalk, 'doubleit');
echo "<br><br>";

echo "<br>New Array after Array Map<br><br>";
function tripleIt($n)
{
    return $n * $n * $n;
}

$tripleIta = array_map('tripleIt', $arrWalk);
echo "<pre>";
print_r($tripleIta);
echo "</pre>";
?>

OUTPUT

Original Array
Array
(
    [0] => 1
    [1] => 3
    [2] => 2
    [3] => 4
    [4] => 2
    [5] => 1
    [6] => 5
    [7] => 6
    [8] => 3
    [9] => 4
    [10] => 5
)

After Doubling the array elements:

Double of 1 is:1
Double of 3 is:9
Double of 2 is:4
Double of 4 is:16
Double of 2 is:4
Double of 1 is:1
Double of 5 is:25
Double of 6 is:36
Double of 3 is:9
Double of 4 is:16
Double of 5 is:25

 
New Array after Array Map

Array
(
    [0] => 1
    [1] => 27
    [2] => 8
    [3] => 64
    [4] => 8
    [5] => 1
    [6] => 125
    [7] => 216
    [8] => 27
    [9] => 64
    [10] => 125
)

Leave a comment