Array Iteration

There are many built-in functions in PHP for iterating arrays.

Some of them are:

  • array_map
  • array_filter
  • array_reduce
  • array_walk

array_map

Returns an array which elements are modified in the function.

The modification is specified in the returned value of the function.

The iterated element is accessed as the argument of the function.

Output:

$num is the iterated element of the array (4, 8, 7, 6 and finally 3).

The returned value - $num * 2; multiplies the array element by 2 (turning 4 into 8, 8 into 16, 7 into 14 and so on).

array_filter

Allows filtering specific elements.

if the function returns true - the element will be present in the returned array.

If the function returns false - it will not be present.

For example we can filter the array to return only the even numbers ($num % 2 == 0):

Output:

array_reduce

Accumulates a single value based on a callback function.

It has 2 arguments - the array, function and initial value.

The callback function accepts 4 arguments - total and value which is the accumulated value.

An example of function summing array elements with printing explanations:

Output:

array_walk

array_walk is a function that allows you to iterate over each element of an array and apply a function to modify it's elements (similar to array_map).

Unlike array_map it can also access keys of the array

Iterating through elements

Output:

Passing addional argument

The 3rd argument of the array_walk function (which is optional) can be accesssed inside the callback function as a 3rd argument (after $value and $key):

Output:

Modifying value

Value modification is possible if the $value argument is passed via reference (using &).

Example:

Output: