Log in

View Full Version : Stumped with simple recursive function



mburt
09-25-2011, 03:17 AM
Given:

function table($array) {
foreach ($array as $x) {
if (is_array($x)) {
table($x);
} else echo "<div class=\"table_cell\">$x</div>\n";
} echo "<div class=\"clear\"></div>\n";
}

table(
array(
array("1", "2"),
array("3", "4")
)
);

I don't understand why it produces:

<div class="table_cell">1</div>
<div class="table_cell">2</div>
<div class="clear"></div>
<div class="table_cell">3</div>
<div class="table_cell">4</div>
<div class="clear"></div>
<div class="clear"></div>

I've tried to run through this recursive function mentally but I just can't seem to understand why it produces an extra div.

What I'm trying to do, is write:
<div class="clear"></div> at the end of each sub-array.

Any thoughts anyone?

traq
09-25-2011, 03:40 AM
Given:

function table($array) {
foreach ($array as $x) {
if (is_array($x)) {
table($x);
} else echo "<div class=\"table_cell\">$x</div>\n";
} echo "<div class=\"clear\"></div>\n";
}

table( array( array("1", "2"), array("3", "4") );

I've tried to run through this recursive function mentally but I just can't seem to understand why it produces an extra div.

you are passing three arrays to the function; so logically, div.clear is being output three times.


<div class="table_cell">1</div> <!--$array[0][0]-->
<div class="table_cell">2</div> <!--$array[0][1]-->
<div class="clear"></div> <!--$array[0] (after each child string is processed)-->
<div class="table_cell">3</div> <!--$array[1][0]-->
<div class="table_cell">4</div> <!--$array[1][1]-->
<div class="clear"></div> <!--$array[1] (after each child string is processed)-->
<div class="clear"></div> <!--$array (after each child array is processed)-->

mburt
09-25-2011, 03:43 AM
Any suggestions traq on how I might achieve what I'm looking for? I'm too tired to think, personally... lol

Nile
09-25-2011, 03:45 AM
<?php
function table($array) {
foreach ($array as $x) {
if (is_array($x)) {
table($x);
echo "<div class=\"clear\"></div>\n";
} else {
echo "<div class=\"table_cell\">$x</div>\n";
}
}
}

table(
array(
array("1", "2"),
array("3", "4")
)
);

mburt
09-25-2011, 03:47 AM
Hm, I never thought you could output anything after the table() function is called inside the loop. Works like a charm!

Nile
09-25-2011, 03:48 AM
No Problem! Yeah it's interesting to play around with using recursive functions.