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.
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 )
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);
?>
Array ( [0] => $100.00 [1] => $200.00 [2] => $300.00 )
Detail | array_map | array_walk |
---|---|---|
output array element | Input array values remain same | Input array values updated |
return value | New array | Boolean: True or False |
Input Number of arrays | One or more | One only |
Extra Parameter | No | Yes |