The array_walk() function is an inbuilt function in PHP. The array_walk() function walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element’s keys and values are parameters in the callback function.
Syntax:
boolean array_walk($array, myFunction, $extraParam)
Parameters: This function accepts three parameters as described below:
-
$array: This is a mandatory parameter and specifies the input array.
- myFunction: This parameter specifies the name of the user-defined function and is also mandatory. The user-defined function generally excepts two parameters of which the first parameter represent the array’s values and the second parameter represents the corresponding keys.
- $extraparam: This is an optional parameter. It specifies an extra parameter to the user-defined function in addition to the two parameters, array keys and values.
Return value: This function returns a boolean value. It returns TRUE on success or FALSE on failure.
Below programs illustrate the array_walk() function:
Program 1:
<?php
function myfunction( $value , $key )
{
echo "The key $key has the value $value \n" ;
}
$arr = array ( "a" => "yellow" , "b" => "pink" , "c" => "purple" );
array_walk ( $arr , "myfunction" );
?>
|
Output:
The key a has the value yellow
The key b has the value pink
The key c has the value purple
Program 2:
<?php
function myfunction( $value , $key , $extraParam )
{
echo "The key $key $extraParam $value \n" ;
}
$arr = array ( "a" => "yellow" , "b" => "pink" , "c" => "purple" );
array_walk ( $arr , "myfunction" , "has the value" );
?>
|
Output:
The key a has the value yellow
The key b has the value pink
The key c has the value purple
Program 3:
<?php
function myfunction(& $value , $key )
{
$value = $value + 10;
}
$arr = array ( "first" =>10, "second" =>20, "third" =>30);
array_walk ( $arr , "myfunction" );
print_r( $arr );
?>
|
Output:
Array
(
[first] => 20
[second] => 30
[third] => 40
)
Reference:
http://php.net/manual/en/function.array-walk.php
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2023
Like Article
Save Article