0

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 HTML 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>";
}
1
  • echo is not a function, and you mean <br />. Commented Jun 13, 2011 at 14:28

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@BenMatewe: No worries. Don't forget to check out arrays.
Thanks. They certainly are very powerful and have shrinked my code dramatically.
0

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.

2 Comments

It can work. It's not the nicest approach, but "this won't work" is incorrect.
Oh. I had to test it myself until I believed it, but you're right. Anyways, arrays are the thing to use here.
0

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

1 Comment

Thanks for the input. Point on arrays noted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.