array_walk

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] => 3 [Second] => 6 [Third] => 9 )

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


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




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