Page 1 of 1
how to write this in a for loop?
Posted: Wed May 14, 2003 1:21 pm
by jiehuang001
I want to do something such as:
echo $var1;
echo $var2;
echo $var3;
Here is the for loop that I tried to achieve the above goal:
for ($i=1; $i<=3; $i++){
echo $var.$i;
}
But it didn't work. Please tell me what is the right way.
Thanks.
Jie Huang
Posted: Wed May 14, 2003 1:29 pm
by Sinnix
Try using an array instead.
Code: Select all
<?php
$var[1] = 5;
$var[2] = 10;
$var[3] = 15;
for ($x=1; $x<=3; $x++)
{
echo ("value: ".$var[$x]."<br>");
}
?>
Posted: Wed May 14, 2003 1:33 pm
by twigletmac
Have a read of:
http://www.php.net/manual/en/language.v ... riable.php
(arrays are much easier to work with though)
Mac
Posted: Wed May 14, 2003 7:40 pm
by McGruff
for ($i=1; $i<=3; $i++){
echo ${'var'.$i};
}
Posted: Thu May 15, 2003 3:06 am
by twigletmac
for ($i=1; $i<=3; $i++){
echo ${'var'.$i};
}
<moan> Is there something wrong with trying to help people figure it out for themselves - once they've tried and if they've failed then giving them more direct help is often appropriate. Telling someone to RTFM is rude but giving a link to the exact information they'll need to fix their code does at least mean that they might learn something more than if they just copy and paste. </moan>
Mac
Posted: Thu May 15, 2003 3:28 am
by Gleeb
I completely agree. The best way to learn is not to be told how, but to find out for yourself, and to understand not that it works, but why it works.
Posted: Thu May 15, 2003 6:22 pm
by McGruff
I just scribbled out the answer without really thinking about it. Sometimes it's good to have a link to the manual AND an example which shows how that applies to the specific problem but I take your point.
How does the saying go:
"give a man a fish and you feed him for a day;
teach a man to fish and in ten years he'll have hoovered up the whole damn marine ecosystem."
Oh well. Something like that.[/quote]
Posted: Fri May 16, 2003 2:29 am
by twigletmac
I'm sorry McGruff, it wasn't totally aimed at you but at the general trend of people posting cut-and-paste code when others have tried to be explicit about where and how people can figure it out for themselves. It just seems to happen a lot and it can be frustrating.
I think it's time I posted some guidelines (not rules) for the forum so that I can extend on my sig and hopefully get some feedback from the other members of the forum on how they want to see things done.
Mac