lovespring lovespring - 3 months ago 13
PHP Question

Can array_walk be nested in php?

I mean:

array_walk($arr1,function(){
//point 1
array_walk($arr2,function(){
//point 2
});
});


It seems this cannot work. the code just run in "point 1" and never run in "point 2".

is this a php bug?

thanks for all!

I find the reason, I have to use the "use(&$arr2)" in the first anonymos function defination, then the inner anonymos function can use this variables.

My php version is 5.6

Answer

Try this:

$arr1 = array("1", "2");
$arr2 = array("22", "432");

/*
 * Specify the second walkway array as the
 * reference param of the callback function
 * if you want to manipulate it. Otherwise,
 * just pass $arr2.
 */
array_walk($arr1, function ($item1, $key, &$arr2) {

    // Point 1
    echo "$item1<br>";

    array_walk($arr2, function ($item2, $key1) {

        // Point 2
        echo "$item2<br>";

    });
}, $arr2); // Pass the other array to walk in within the walkway

This will print:

1
22
432
2
22
432