array_map()

It’s really useful when you want to perform a specific operation on every element of an array. If you want to perform a specific action on each element of an array instead of iterating over each element of an array it is better to use an array_map() function which is built for this. An array_map() function returns an array containing the results of applying the callback function over the array.

Syntax:

array_map(function_name, array1, array2, array3, …)

Parameters:

  • function_name: A callable function to apply to each element in each array.
  • array1: It is an array of elements to which the callback function applies.

Note: We can send multiple arrays in the array_map() function.

<?php
  function square($n) {
    return ($n * $n);
  }
   
  $a = [1, 2, 3, 4, 5];
  $b = array_map('square', $a);
  print_r($b);
?>

array_reduce()

As the name suggests, an array_reduce() function reduces the array to a single value by performing the given operation. The array_reduce() applies the callback function to the elements of the array and gives output as a single value

Syntax:

array_reduce(array, myfunction, initial)

Parameters:

  • array: It is the input array that will be reduced to a single value.
  • myfunction: It is a callback function that determines how the array should be reduced.
  • initial: It is an optional value that will be used at the beginning of the process, or as a final result in case the array is empty
<?php 
  function add($num1, $num2) {
    $num1 += $num2; 
    return $num1; 
  
  $a = array(1, 2, 3, 4, 5, 6); 
  $num1 = array_reduce($a, "add"); 
  echo $num1;
?>

array_walk()

It applies a user-defined function to every member of an array. The array’s keys and values are parameters in the function. The array_walk() function is not affected by the internal array pointer of the array. It will traverse through all the elements. The array_map() cannot operate with the array keys, while the array_walk() function can work with the key values pair.

Syntax:

array_walk(array, myfunction, parameter…)

Parameters:

  • array: The input array.
  • myfunction: Name of the function

parameter: Specifies a parameter to the user-defined function. You can assign multiple parameters

<?php
function myfunction($value,$key) {
    echo "Geeksforgeeks $key is about $value \n";
}
$articles = array(
    "article-1" => "HTML",
    "article-2" => "CSS",
    "article-3" => "PHP"
); 
array_walk($articles,"myfunction");
?>