homepage Welcome to WebmasterWorld Guest from 54.226.168.96
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Accredited PayPal World Seller

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Recursive foreach()
Readie




msg:4143673
 7:46 pm on May 29, 2010 (gmt 0)

I had reason to need a recursive foreach function that was similar to array_walk_recursive - but I actually needed the key name of the lower leveled arrays as well.

So, stripped down a little bit, but preserving the key functionality:

[pre]function recursive_foreach($array) {
$out = '';
foreach($array as $key => $value) {
$out .= '<br>' . $key;
if(!is_array($value)) {
$out .= ' - ' . $value;
} else {
$out .= recursive_foreach($value);
}
}
return $out;
}[/pre]

Test:
[pre]$the_array = array(
0 => array(
0 => 'a',
1 => 'b',
'c' => 3,
'd' => array(
3 => 2,
'a' => 'b',
'c' => 2
)
),
1 => array(
'e',
'f' => 'g',
'h' => 2,
65 => 35,
32 => 'i'
),
'foo' => array(
'j',
'k' => 'l'
),
'bar'
);

echo recursive_foreach($the_array);[/pre]

Output:
0
0 - a
1 - b
c - 3
d
3 - 2
a - b
c - 2
1
0 - e
f - g
h - 2
65 - 35
32 - i
foo
0 - j
k - l
2 - bar

Just thought I'd share incase anyone finds themselves needing something similar :)

 

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved