-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++;
}
AVGG
  • 21
  • 5

2 Answers2

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"};
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
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++;
}
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95