AppDividend
Latest Code Tutorials

PHP array_walk: How to Use array_walk() Function

The array_walk() function runs each array item in the user-defined function. The user-defined function takes an array’s values and keys as parameters.

PHP array_walk

PHP array_walk() is a built-in function that walks through an entire array regardless of pointer position and applies the callback function or user-defined function(UDF) to every element of the array. The array_walk() is not affected by the internal array pointer of the array.

Syntax

See the below syntax.

array_walk(array,myfunction,parameter...)

Arguments

The array parameter is required and specifies an array.

The myfunction parameter is required and the name of a user-defined function.

The parameter is optional, and it specifies the parameter to the user-defined function(UDF). You can assign one parameter to a function or as many as you like.

Example

See the following example.

<?php

// app.php

function demo($value, $key, $p)
{
  echo "$key $p $value"."\n";
}

$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran'];
array_walk($MVP, "demo", "has the value");

See the below output.

PHP array_walk Example

The function returns the boolean value. In addition, it returns the TRUE value on success or FALSE on failure.

Change an array element’s value.

We can change all the array elements using the array_walk() function.

We need to pass the &$value instead of just $value. Notice the & difference.

See the following example.

<?php

// app.php

function demo(&$value, $key)
{
  $value = 'Hound';
}

$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran'];
array_walk($MVP, "demo", "has the value");
print_r($MVP);

See the output below.

Change an array element's value

In the above example, all the values are replaced by the Hound value. 

It’s worth noting that array_walk cannot be used to change the keys in an array. The array_walk() function may be defined as (&$value, $key) but not (&$value, &$key). Even though PHP does not complain or warn, it does not modify a key. PHP ignored the arguments type when using the array_walk() even if there was declare(strict_types=1). 

If you want to unset items from a callback function, you may need array_filter. The array_walk() function cannot modify / change / reindex keys.

It can be advantageous to pass the third (optional) parameter by reference while modifying it permanently in the callback function. However, this will cause passing the modified parameter to the next iteration of array_walk().

That’s it.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.