W3Schools.com

PHP array_walk() Function


PHP Array Reference Complete PHP Array Reference

Definition and Usage

The array_walk() function runs each array element in a user-made function. The array's keys and values are parameters in the function. Returns True or False

Syntax

array_walk(array,function,parameter...)

Parameter Description
array Required. Specifying an array
function Required. The name of the user-made function
parameter Optional. Specifies a parameter to the user-made function


Tips and Notes

Tip: You can assign one parameter to the function, or as many as you like.

Note: You can change an array element's value in the user-made function by specifying the first parameter as a reference: &$value. (See example 3)


Example 1

<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");
?>

The output of the code above will be:

The key a has the value Cat
The key b has the value Dog
The key c has the value Horse


Example 2

With a parameter:

<?php
function myfunction($value,$key,$p)
{
echo "$key $p $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction","has the value");
?>

The output of the code above will be:

a has the value Cat
b has the value Dog
c has the value Horse


Example 3

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

<?php
function myfunction(&$value,$key)
{
$value="Bird";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");
print_r($a);
?>

The output of the code above will be:

Array ( [a] => Bird [b] => Bird [c] => Bird )


PHP Array Reference Complete PHP Array Reference
WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE