PHP array_walk() function “applies a callback function(user-defined function) to every element of the array.”
Syntax
array_walk($array, callback, parameter...)
Parameters
- $array(required): It is an input array.
- callback(required): It is the name of a user-defined function.
- 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 Representation
Example 1: How to Use array_walk() function
<?php
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");
Output
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 parameter
<?php
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');
Output
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.
<?php
function demo(&$value, $key)
{
$value = 'Hound';
}
$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran'];
array_walk($MVP, "demo");
print_r($MVP);
Output
Array
(
[0] => Hound
[1] => Hound
[2] => Hound
[3] => Hound
[4] => Hound
)
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.