2

The for loop fails because "$" is an invalid variable character:

<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 0; $i < 3; $i++) {
    echo $num$i . "<br>";
}
?>

(I didn't understand this question)

Community
  • 1
  • 1
Rublacava
  • 414
  • 1
  • 4
  • 16
  • 3
    You're looking for [variable variables](http://php.net/manual/en/language.variables.variable.php). But in almost any case, using an array is better. – Qirel Jan 09 '16 at 16:04

6 Answers6

3
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 1; $i <=3; $i++) {
    $num = 'num' . $i;
    echo ${$num} . "<br>";
}

But using array is simpler:

$nums = array("Number 1", "Number 2","Number 3");
for ($i = 0; $i <3; $i++) {
    echo $nums[$i] . "<br>";
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

You're asking for variable variables. An example, like this

for ($i=1; $i<=3; $i++) {
    echo ${"num".$i}."<br />";
}

Usage of variable variables can often result in messy code, so usage of an array is often considered better practice.

Should you want to try out an array, you can do it like this.

$number = array("Number 1", "Number 2", "Number 3");

You can then use a foreach-loop to echo it out, like this

foreach ($number as $value) {
    echo $value."<br />";
}

or as you're using, a for-loop

for ($i=0; $i <= count($number); $i++) {
    echo $number[$i]."<br />";
}
Qirel
  • 25,449
  • 7
  • 45
  • 62
0

What you are trying to do is variable variables (but I recommend you to use an array).

Here is how you should do it.

<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 0; $i < 3; $i++) {
    echo ${"num".$i} . "<br>";
}
Fawzan
  • 4,738
  • 8
  • 41
  • 85
0

Why don't you use an array? Try this-

<?php 
  $num = Array("Number 1","Number 2","Number 3");
  for ( $i = 0; $i< 3; $i++ ){
    echo $num[$i]."<br>";
  }
?>
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
0
<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 1; $i <= 3; $i++) {
    echo ${"num".$i} . "<br>";
}

?>
Vigneswaran S
  • 2,039
  • 1
  • 20
  • 32
0

Have a look at this answer: https://stackoverflow.com/a/9257536/2911633

In your case it would be something like

for($i = 1; $i <= 3; $i++){
     echo ${"num" . $i} . "<br/>";
}

But I would recommend you use arrays instead of this method as arrays give you better control.

Community
  • 1
  • 1
Igor Ilic
  • 1,370
  • 1
  • 11
  • 21