PHP foreach() with arrays within arrays? PHP foreach() with arrays within arrays? php php

PHP foreach() with arrays within arrays?


That's a perfect job for Iterators:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));foreach($iterator as $key => $value) {    echo "$key => $value\n";}

See Introduction to SPL Iterators and Live Demo on codepad

EDIT: the alternative would be array_walk_recursive as show in Finbarr's answer below


See array_walk_recursive - a PHP library function that recursively calls a user defined function against a provided array.

From PHP docs:

<?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');?>

Output:

a holds appleb holds bananasour holds lemon

Note that Any key that holds an array will not be passed to the function..

EDIT: slightly less ugly example:

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


Typically, in this kind of situation, you'll have to write a recursive function -- which will deal with an item if it's not an array ; and call itself on an item if it's an array.


Here, you could have something like this :

$arr = array(    'languages' => array(        'php', 'mysql', 'inglip',     ),     'rates' => array(        'incall' => array('1hr' => 10),         'outcall' => array('1hr' => 10),     ), );function recurse($item) {    foreach ($item as $key => $value) {        if (is_array($value)) {            recurse($value);        } else {            echo "$key : $value\n";        }    }}


And calling this recursive function on your array :

recurse($arr);

Would get you :

0 : php1 : mysql2 : inglip1hr : 101hr : 10