All Your Protection Under One Roof
0

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)

1
2
$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>";
}
All Your Protection Under One Roof
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>";
}
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>";
  }
?>
0
<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

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

?>
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.

0

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 />";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.