Computer >> Computer tutorials >  >> Programming >> PHP

array_walk_recursive() function in PHP


The array_walk_recursice() function applies a user function recursively to every member of an array.

Syntax

array_walk_recursive(arr, custom_func, parameter)

Parameters

  • arr − The specified array. Required.

  • custom_func − The user defined function. Required.

  • parameter − The parameter to be set for the custom function. Optional.

Return

The array_walk_recursive() function returns TRUE on success or FALSE on failure.

Example

The following is an example −

<?php
function display($val,$key) {
   echo "Key $key with the value $val<br>";
}
$arr1 = array("p"=>"accessories","q"=>"footwear");
$arr2 = array($arr1,"1"=>"electronics");
array_walk_recursive($arr2,"display");
?>

Output

Key p with the value accessories
Key q with the value footwear
Key 1 with the value electronics

Example

Let us see another example which pass another parameter −

<?php
function display($val,$key, $extra) {
   echo "Key $key $extra $val<br>";
}
$arr1 = array("p"=>"accessories","q"=>"footwear");
$arr2 = array($arr1,"5"=>"electronics");
array_walk_recursive($arr2,"display", "with value");
?>

Output

Key p with the value accessories
Key q with the value footwear
Key 5 with the value electronics