Hướng dẫn
Quảng cáo

Hàm array_walk() trong PHP

Hướng dẫn cách sử dụng hàm array_walk() về mảng trong lập trình PHP

Tác dụng của hàm array_walk()

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+


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.

// 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");


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:

// 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");

Bài viết này đã giúp ích cho bạn?

Bài viết mới