user3550479
user3550479

Reputation: 33

print value of a variable that is composed for a string into a For Loop

In this loop, I'm trying to take the value of the variable, but to save code I want to use a For Loop to print it concatenating part of the variable with a number genereted into the loop. This is my Try.

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

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

the result that I'm geting is

$x0$x1$x2$x3$x4

I want it to end up like this:

0123

Upvotes: 3

Views: 72

Answers (3)

Vikas Umrao
Vikas Umrao

Reputation: 2615

Try this :

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

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

    }

Upvotes: 2

Sagar
Sagar

Reputation: 647

Try this Code:

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

Upvotes: 0

Kevin
Kevin

Reputation: 41885

Its supposed to be:

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

Sidenote: You'll have to define $x4 or terminate it to < 4 so you won't get a undefined index.

Upvotes: 2

Related Questions