PHP array_walk() Function

PHP array_walk() function “applies a callback function(user-defined function) to every element of the array.”


array_walk($array, callback, parameter...)


  1. $array(required): It is an input array.
  2. callback(required): It is the name of a user-defined function.
  3. parameter(optional): If it is supplied, it will be passed as the third parameter to the user function.

Return value

It returns a boolean value. TRUE on success or FALSE on failure.

Visual RepresentationVisual Representation of PHP array_walk() Function

Example 1: How to Use array_walk() function


function demo($value, $key)
 echo "The key $key has the value $value \n";

$MVP = ['a'=>'Arya','b'=>'Jon', 'c'=>'Sansa', 'd'=>'Tyrion'];
array_walk($MVP, "demo");


The key a has the value Arya 
The key b has the value Jon 
The key c has the value Sansa 
The key d has the value Tyrion 

Example 2: Using the third parameterVisual Representation of Using the third parameter


function demo($value, $key, $p)
 echo "The key $key and $value $p \n";

$MVP = ['a'=>'Arya','b'=>'Jon', 'c'=>'Sansa', 'd'=>'Tyrion'];
array_walk($MVP, "demo", 'have been paired together');


The key a and Arya have been paired together 
The key b and Jon have been paired together 
The key c and Sansa have been paired together 
The key d and Tyrion have been paired together

Example 3: Change an array element’s value.

We must pass the &$value instead of just the $value. 


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

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


 [0] => Hound
 [1] => Hound
 [2] => Hound
 [3] => Hound
 [4] => Hound

That’s it.

Leave a Comment

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