PHP array_walk() Function

Definition

The array_walk() function runs a user-defined function on each array element.

The array's keys and values are parameters in the function.

We can change the value in the user-defined function by specifying the first parameter as a reference: &$value.

Note

To walk an array inside an array, use the array_walk_recursive() function.

Syntax

PHP array_walk() Function has the following syntax.

array_walk(array,myfunction,parameter...)

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to walk on
myfunctionRequired.The name of the user-defined function
parameter,...Optional.A parameter to the user-defined function. You can assign one parameter to the function, or as many as you like

Example 1

Map an array with user defined function


<?php/*  www  .jav a 2s . com*/
    function myfunction($value,$key){
        echo "The key $key has the value $value<br>";
    }
    $a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
    array_walk($a,"myfunction");
?>

The code above generates the following result.

Example 2

With a parameter:


<?php//from  w w w . jav  a  2  s .  c o m
    function myfunction($value,$key,$p){
       echo "$key $p $value ==";
    }
    $a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
    array_walk($a,"myfunction","has the value");
?>

The code above generates the following result.

Example 3

Change an array element's value. (using the &$value)

<?php/*ww  w .  j a  v a2s  .c o m*/
    function myfunction(&$value,$key){
       $value=" added";
    }
    $a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
    array_walk($a,"myfunction");
    print_r($a);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions