How the recursive_walk_array works?

Hi,

I cant understand: array_walk_recursive(….):

Following is my program:

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>

I am getting the following output:

a holds apple b holds banana sour holds lemon

The definition says that array_walk_recursive applies a user function to every member of an array.
Here the function name is test_print(…), two arguments: $item and $key.
The command is:
array_walk_recursive($fruits, ‘test_print’);
So we have to deal with $fruits array.

$fruits = array(‘sweet’ => $sweet, ‘sour’ => ‘lemon’);

I cant understand how the test_print(…) function handles the $fruits array. Somebody please guide me.

Zulfi.

Instead of using array_walk_recursive(…) you could create your own recursive(…) function:

<?php declare(strict_types=1);
error_reporting(-1);
ini_set('display_errors', 'true');

$sweet  = array('a'     => 'apple', 'b'    => 'banana');
$fruits = array('sweet' => $sweet,  'sour' => 'lemon');

//==================================
function test_print($item, $key)
{
  echo "<br>\$key: $key holds \$item: $item\n";
}

//==================================
function recursive($fruits)
{
  foreach($fruits as $key => $item):
    if( is_array($item) ):
      recursive($item); 
    else:  
      echo "<br>\$key: $key holds \$item: $item\n";
    endif;  
  endforeach;     
}

echo '<pre> <b> $sweet  ==> </b>';  print_r($sweet);
echo '<pre> <b> $fruits ==> </b>'; print_r($fruits);
echo '<hr>';

echo '<b>function array_walk_recursive() ==> </b><hr>';
  array_walk_recursive($fruits, 'test_print');

echo '<br><br><hr>';
echo '<b>function recursive() ==> </b><hr>';
  recursive($fruits);

Output:

  $sweet  ==> Array
(
    [a] => apple
    [b] => banana
)

  $fruits ==> Array
(
    [sweet] => Array
        (
            [a] => apple
            [b] => banana
        )

    [sour] => lemon
)
function array_walk_recursive() ==> 
$key: a holds $item: apple

$key: b holds $item: banana

$key: sour holds $item: lemon


function recursive() ==> 
$key: a holds $item: apple

$key: b holds $item: banana

$key: sour holds $item: lemon
1 Like

The answer is in the manual page you got this code from

You may notice that the key ’ sweet ’ is never displayed. Any key that holds an array will not be passed to the function.

See https://www.php.net/manual/en/function.array-walk-recursive.php

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.