Categories
PHP

aray_map() and array_walk()

How to modify all array elements, or nested array elements using array_map() and array_walk() functions. What is the difference between array_walk() and array_map() functions.

  1. Modify all array elements using array_map()
  2. Working with nested arrays using array_map()
  3. Iterate or print multiple arrays using array_map()
  4. Modify all array elements using array_walk()
  5. Comparing array_walk() and array_map()

Modify all array elements with array_map()

<?php
//Syntax
array_map(?callable $callback, array $array, array ...$arrays): array
  1. The array_map() function applies a $callback function to all elements of the array $array and returns a new array with the keys intact.
  2. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map() function.
  3. Associative array keys are converted to the indexed key if multiple arrays (arguments) are passed to the callback function.
  4. array_map() function does not deal with array keys, use the array_walk() function if you need to deal with array keys.

Sometimes, data in an array has to be preprocessed before it can be used. For example, the data coming from the user forms can be sanitized before it is used. To do so, every array element must be touched. However, it is not required that you do a cumbersome for, foreach, or while loop, PHP offers built-in functionality for this, see example:

Applying htmlspecialchars() to all elements of an array

<?php
  $a = array('harmless', '<bad>', '>>click here!<<');
  $b = array_map('htmlspecialchars', $a);
  echo implode(' ', $b);

In the preceding listing, all values in the array are converted into HTML entities using htmlspecialchars().

Mapping Nested Arrays with array_map()

If, however, the array turns out to be a nested one, the tactic has to be changed a little. Then a recursive function can be used. If an array element is a string, it is HTML encoded. If it’s an array, the recursive function calls itself on that array. See example:

Recursively applying htmlspecialchars() to all elements of a nested array

<?php
  function sanitize_recursive($s) {
    if (is_array($s)) {
      return(array_map('sanitize_recursive', $s));
    } else {
      return htmlspecialchars($s);
    }
  }

  $a = array(
    'harmless' =>
      ['no', 'problem'],
    'harmful' =>
      ['<bad>', '> <worse> <<-']
  );
  $b = sanitize_recursive($a);
  echo '<pre>' . print_r($a, true) . '</pre>';

Using multiple arrays with array_map()

Sometimes two or more arrays of the same length need to be iterated together, array_map() function is the simplest way to accomplish this:

<?php
 $a = ['one', 'two', 'three'];
 $b = ['i', 'ii', 'iii'];
 $c = ['I', 'II', 'III'];

 function mapThree($val_a, $val_b, $val_c){
  return "$val_a, $val_b, $val_c";
 }

 $d = array_map ('mapThree', $a, $b, $c);
 print_r($d);

/*Prints
Array
(
    [0] => one, i, I
    [1] => two, ii, II
    [2] => three, iii, III
)
*/

array_walk()

<?php
//Syntax
array_walk(array|object &$array, callable $callback,
           mixed $arg = null): bool

Similar to array_map(), the array_walk() function applies a callback function to each element of an array. By default, array_walk() passes two arguments to the callback: the element’s value and key. An optional third argument can also be used.

Printing array elements using array_walk()

<?php
  function printElement($v, $k) {
    echo "$k = $v<br>";
  }
  $a = array('one'=>1, 'two'=>2, 'three'=>3);
  $a = array_walk($a, 'printElement');
/*Prints:
one = 1
two = 2
three = 3*/

Modifying array elements using array_walk()

<?php
 function cb(&$v){
  $v *= 2;
 }
 
 $a = [1,2,3];
 array_walk($a, 'cb');
 
 print_r($a);
 /*Prints;
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)*/

The array_walk() function can take an extra argument to pass to the callback function, see the following example.

Modifying array elements using array_walk() third argument

<?php
 function cb(&$v, $k, $i){
  $v *= $i;
 }
 
 $a = [1,2,3];
 //Using third argument
 array_walk($a, 'cb', 5);
 
 print_r($a);
 /*Prints: 
Array
(
    [0] => 5
    [1] => 10
    [2] => 15
) */

Comparing array_walk and array_map

A few differences between the array_map() and array_walk() are:

  1. array_map() cannot change the values inside the input array
    array_walk() can change the value inside the input array.
  2. array_map() returns a new array.
    array_walk() returns true.
  3. array_map() cannot process array keys.
    array_walk() can process array keys.
  4. array_map() can process multiple arrays and you can use it as an iterator to iterate multiple arrays at the same time.
    array_walk() accepts only one array as an argument.
  5. array_map() can receive multiple arrays, the number of parameters that the callback function accepts should match the number of arrays passed to array_map().
    array_walk() can receive an optional parameter to pass to the callback as the third parameter.

Working with arrays: