Page 1 of 1

PHP Loop within a loop

Posted: Wed May 19, 2010 10:17 pm
by Kraegan

Code: Select all

$id=1;
while ($id < 13) {
	$i=0;
	while ($i < $num_1) {
		echo $_1[$i][Name].' ';
		$i++;
	}
	echo '<br /><br /><br /><br />';
$id++;
}
Above is a brief synopsis of the code that I’m experimenting with. In short, I would like the first loop to to change the state of the inner loop’s actual variable name, not the variable itself. Where ever there is a “1” in the inner variable it would actually take the state of the $id variable.
I.E.

On first pass: $num_1 and $_1
On second pass: $num_1 and $_2 etc.


What I’m attempting to achieve is a shorthand for the following code…

Code: Select all

//January---------------------------------------
	$i=0;
	while ($i < $num_1) {
		echo $_1[$i][FairName].' ';
		echo $_1[$i][StartDate].' - ';
		echo $_1[$i][FairEndDate].'<br />';
		$i++;

}
//February---------------------------------------
	$i=0;
	while ($i < $num_2) {
		echo $_2[$i][FairName].' ';
		echo $_2[$i][StartDate].' - ';
		echo $_2[$i][FairEndDate].'<br />';
		$i++;

}
//March---------------------------------------
	$i=0;
	while ($i < $num_3) {
		echo $_3[$i][FairName].' ';
		echo $_3[$i][StartDate].' - ';
		echo $_3[$i][FairEndDate].'<br />';
		$i++;

Re: PHP Loop within a loop

Posted: Wed May 19, 2010 10:21 pm
by Benjamin
You are wanting to use variable variables.

Code: Select all

$foo = 'bar';
$you = 'foo';

echo $$you;

Re: PHP Loop within a loop

Posted: Thu May 20, 2010 12:16 am
by Kraegan

Code: Select all

	$$_1= '$_'.$id;
	$$num_1 = '$num_'.$id;

	$i=0;
	while ($i < ${$num_1}) {
		echo ${$_1}[$i][FairName].' ';
		echo ${$_1}[$i][StartDate].' - ';
		echo ${$_1}[$i][FairEndDate].'<br />';
		$i++;
	}
@Benjamin
Very close, thank you; however, I need PHP to recognize that literal variable is changing and not just the output value. What I’m trying may not be possible. I'll continue to research this a bit more.

Re: PHP Loop within a loop

Posted: Thu May 20, 2010 12:34 am
by Benjamin
Right, you can do that with variable variables.