String and variable to output variable
My intention is to output $car1
, $car2
to have a list in the HTML output e.g Toyota, BMW, ...However i am getting $car2
in the HTM开发者_运维问答L output. How does one make the loop output $car1
, $car2
... Is there another function other than echo to do this?
for ($i = 1; $i <= 10; $i++) {
echo $car . $i;
echo "<br>";
}
You're looking for variable variables:
for ($i = 1; $i <= 10; $i++) {
$varName = "car" . $i;
echo $$varName . "<br />";
}
or, for short:
for ($i = 1; $i <= 10; $i++) {
echo ${'car' . $i} . "<br />";
}
You'd be better off with arrays, though.
I'm guessing:
You have a bunch of variables called:
- $car1
- $car2
- $car3
- $car4
- ...
And now you want to output them using this:
echo $car . $i;
So you want the code the generate $car1
for you?
This won't work. You shouldn't do this. You should use an array to save your cars. This can be looped over using a for or foreach-loop.
As Tomalak mentioned, arrays should be used in this case.
$car[] = "Honda";
$car[] = "Toyota";
$car[] = "Dodge";
$car[] = "Ford";
for($i = 0; $i<=3; $i++){
echo $car[$i];
echo "<br>";
}
Output:
Honda
Toyota
Dodge
Ford
精彩评论