Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_walk()

Example

Apply a user-defined function to each element of an array.

<?php
function myfunction($value,$key)
{
echo “The key $key has the value $value<br>”;
}
$a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”);
array_walk($a,“myfunction”);
?>

Definition and Usage

The array_walk() function applies a user-defined function to each element of an array, with the array’s keys and values as parameters.

Note: You can modify an array element’s value in the user-defined function by using a reference for the first parameter: &$value (see Example 2).

Tip: For handling multidimensional arrays (arrays within arrays), use the array_walk_recursive() function.

Syntax

array_walk(array, myfunction, parameter…)

Parameter Values

Parameter

Description

array

Required. Specifying an array

myfunction

Required. The name of the user-defined function

parameter,…

Optional. Specifies a parameter to the user-defined function. You can assign one parameter to the function, or as many as you like

Technical Details

Return Value:

Returns TRUE on success or FALSE on failure.

PHP Version:

4+

More Examples

Example 1

<?php
function myfunction($value,$key,$p)
{
echo “$key $p $value<br>”;
}
$a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”);
array_walk($a,“myfunction”,“has the value”);
?>

Example 2

Modify an array element’s value (note the use of &$value).

<?php
function myfunction(&$value,$key)
{
$value=“yellow”;
}
$a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”);
array_walk($a,“myfunction”);
print_r($a);
?>