How to use array_reduce() function in php?

array_reduce() Method: 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.

1. Syntax:


array_reduce(array, myfunction, initial)


    - 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.

2. Example:


  function add($num1, $num2) {
    $num1 += $num2;  
    return $num1;  
  $a = array(1, 2, 3, 4, 5, 6);  
  $num1 = array_reduce($a, "add");  
  echo $num1;