PHP Loop within a loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Kraegan
Forum Newbie
Posts: 2
Joined: Wed May 19, 2010 9:36 pm

PHP Loop within a loop

Post 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++;
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP Loop within a loop

Post by Benjamin »

You are wanting to use variable variables.

Code: Select all

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

echo $$you;
Kraegan
Forum Newbie
Posts: 2
Joined: Wed May 19, 2010 9:36 pm

Re: PHP Loop within a loop

Post 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.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP Loop within a loop

Post by Benjamin »

Right, you can do that with variable variables.
Post Reply