Open In App

PHP array_walk_recursive() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The array_walk_recursive() function is an inbuilt function in PHP. The array_walk_recursive() function walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array recursively. The array element’s keys and values are parameters in the callback function. The difference between this function and the array_walk() function is that it will recurse into deeper arrays (an array inside an array).

Syntax:

boolean array_walk_recursive($array, myFunction, $extraParam)

Parameters: This function accepts three parameters as described below:

  1. $array: This is a mandatory parameter and specifies the input array.
  2. myFunction: This parameter specifies the name of the user-defined function and is also mandatory. The user-defined function generally excepts two parameters of which the first parameter represent the array’s values and the second parameter represents the corresponding keys.
  3. $extraparam: This is an optional parameter. It specifies an extra parameter to the user-defined function in addition to the two parameters, array keys and values.

Return value: This function returns a boolean value. It returns TRUE on success or FALSE on failure.

Below programs illustrate the array_walk_recursive() function:

Program 1:




<?php
  
// PHP program to illustrate 
// array_walk_recursive() function
  
// user-defined callback function
function myFunction($value, $key)
{
    echo "The key $key has the value $value \n";
}
  
// Input arrays
$arr1=array("x"=>"india", "y"=>"Pakistan");
$arr2=array($arr1, "1"=>"China", "2"=>"Japan");
  
// calling array_walk_recursive() without
// extra parameter
array_walk_recursive($arr2, "myFunction");
  
?> 



Output:

The key x has the value india 
The key y has the value Pakistan 
The key 1 has the value China 
The key 2 has the value Japan

Program 2:




<?php
  
// PHP program to illustrate 
// array_walk_recursive() function
  
// user-defined callback function 
// with extra parameter
function myFunction($value, $key , $extraParam)
{
    echo "The key $key $extraParam $value \n";
}
  
// Input arrays
$arr1=array("x"=>"india", "y"=>"Pakistan");
$arr2=array($arr1, "1"=>"China", "2"=>"Japan");
  
// calling array_walk_recursive() with
// extra parameter
array_walk_recursive($arr2, "myFunction", "has the value");
  
?> 


Output:

The key x has the value india 
The key y has the value Pakistan 
The key 1 has the value China 
The key 2 has the value Japan

Reference:
http://php.net/manual/en/function.array-walk-recursive.php



Last Updated : 20 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads