Print the value of the variable that is composed for the string in For Loop

In this loop, I am trying to accept the value of a variable, but to save the code, I want to use For Loop to concatenate the part of the variable with the number generated in the loop. This is my attempt.

<?php
$x0 = 0;
$x1 = 1;
$x2 = 2;
$x3 = 3;

for ($i=0; $i < 5; $i++) {
echo '$x'.$i;   
}
?>

      

the result i get is

$ x0 $ x1 $ x2 $ x3 $ x4

I want it to end like this:

0123

+3


source to share


3 answers


It was assumed that:

for ($i=0; $i < 5; $i++) {
    echo ${"x$i"};
}

      



Sidenote: you need to define $x4

or complete it before < 4

so that you don't get undefined index.

+2


source


Try the following:



    $x0 = 0;
    $x1 = 1;
    $x2 = 2;
    $x3 = 3;

    for ($i=0; $i < 5; $i++) {
    $y='x'.$i;
    if(isset($$y)){
     echo $$y;
     }

    }

      

+2


source


Try this code:

<?php
$x0 = 0;
$x1 = 1;
$x2 = 2;
$x3 = 3;
$string = '';
for ($i=0; $i < 5; $i++) { 
$string .= $i;
}
echo $string;  
?>

      

0


source







All Articles