-1

I use a loop and 8 variables with almost the same name.

$date1,$date2,$date3,etc..

Now I want to do in the loop echo $date$i Any idea how to achieve this ?

The PHP loop :

$i = 1;
while ($i < 8 ) {
echo $date$i;
$i++;
}
8
  • 1
    If you need to number your variables, then you'd be better using an array Commented May 4, 2015 at 11:35
  • concatenate it $date.$i Commented May 4, 2015 at 11:35
  • If yoy really need to use this structure, then use Variable variables Commented May 4, 2015 at 11:35
  • Use arrays instead of indexed variables. Commented May 4, 2015 at 11:35
  • or use the eval function Commented May 4, 2015 at 11:36

2 Answers 2

1

Usually you'll use an array for that:

$data = array('x', 'y', 'z', 'a', 'b', 'c', '1' , '2');
for($i = 0; $i < 8; $i++) {
    echo $data[$i];
}

However if you for whatever reason need 8 variables (I can't see a reason), you need to do it like this:

for($i = 0; $i < 8; $i++) {
    echo ${"data$i"};
}
Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned by others before, a better way to go about this this would be to use arrays. Anyways correct syntax for what you want to do would be

$i = 1;
while ($i < 8 ) {
echo ${"date$i"};
$i++;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.