array_walk(): applies a user-defined callback function to each element in an array

We can create our own function and pass each element of an array through the function.
array_walk(input_array, function, optional_extra_parameter )

Return Value ( boolean ): TRUE on success or FALSE on failure

Let us try this with an example. We will try to add one char 'x' to each element of an array
<?Php
function add_char($str){
$str = $str.'x';
echo $str.'<br>';
}
$a= array(1,2,v,4,7.3,105 ); 

array_walk($a, 'add_char');
?>
The output is here
1x
2x
vx
4x
7.3x
105x
The function array_walk returns TRUE or FALSE based on the success or failure. It does not return a new array with modified elements. You can add the following lines to test your script.
<?Php
function add_char($str){
$str = $str.'x';
echo $str.'<br>';
}
$a= array(1,2,v,4,7.3,105 ); 

if(array_walk($a, 'add_char')){
echo " Success ";
}else{
echo " Failed";
}
?>
The output is here
1x
2x
vx
4x
7.3x
105x
Success
To get a new array with modified elements then we have to use array_map function.

array_walk with optional parameter

function my_function(&$value,$key,$v1){
$value=$value*$v1;
}

$a= array('First'=>1,'Second'=>2,'Third'=>3 ); 

if(array_walk($a, 'my_function',2)){
echo "  Success <br> ";
}else{
echo " Failed <br>";
}
print_r($a);
Output is here
Success
Array ( [First] => 2 [Second] => 4 [Third] => 6 )

Example : Using `array_walk()` to Transform Array Data

This example demonstrates modifying each element in an array using array_walk() to format data. Here, we append a unit to each numeric value.

<?php
$prices = [100, 200, 300];
array_walk($prices, function(&$value) {
    $value = "$" . $value . ".00";  // Append currency format
});
print_r($prices);
?>

Output:

Array ( [0] => $100.00 [1] => $200.00 [2] => $300.00 )

Difference between array_map and array_walk

Read more on array_map()

Detailarray_maparray_walk
output array element Input array values remain sameInput array values updated
return value New arrayBoolean: True or False
Input Number of arrays One or moreOne only
Extra Parameter No Yes
array_map function to get a new array by applying callback function
array_walk_recursive() traversing multi-dimensional array Joining Two Arrays by array_merge
Array REFERENCE
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer