Array Functions
Advertisements

PHP array_walk() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_walk() function apply a user-defined function to every element of an array.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Version: PHP 4+

Syntax

The basic syntax of the array_walk() function is given with:

array_walk(array, callback, userdata);

The following example shows the array_walk() function in action.

<?php
// Defining a callback function
function myFunction($value, $key){
    echo "<p>$key for $value</p>";
}

// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat");
array_walk($alphabets, "myFunction");
?>

Parameters

The array_walk() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
callback Required. Specifies the name of the user-defined callback function. The callback function typically takes on two parameters — the array value being the first, and the key/index second.
userdata Optional. Specifies a parameter to the user-defined callback function. It will be passed as the third parameter to the callback function.

More Examples

Here're some more examples showing how array_walk() function actually works:

You can also pass an indexed array as parameter to this function, as shown here:

<?php
// Defining a callback function
function myFunction($value, $index){
    echo "<p>The value at index $index is $value</p>";
}

// Sample array
$colors = array("red", "green", "blue", "orange");
array_walk($colors, "myFunction");
?>
Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.