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
how to write this in a for loop?
Moderator: General Moderators
-
jiehuang001
- Forum Commoner
- Posts: 39
- Joined: Mon May 12, 2003 12:53 pm
-
Sinnix
- Forum Commoner
- Posts: 43
- Joined: Mon Apr 28, 2003 11:01 am
- Location: Ottawa, ON Canada
- Contact:
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>");
}
?>- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
Have a read of:
http://www.php.net/manual/en/language.v ... riable.php
(arrays are much easier to work with though)
Mac
http://www.php.net/manual/en/language.v ... riable.php
(arrays are much easier to work with though)
Mac
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
<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>for ($i=1; $i<=3; $i++){
echo ${'var'.$i};
}
Mac
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:
How does the saying go:
Oh well. Something like that.[/quote]"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."
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
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
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