2

I'm new in php this is possible?

$value_0 = "0"; 
$value_1 = "1";
$value_2 = "2"; 
$nr = 2;
    for ($i=0; $i <= $nr; $i++)
    {
        echo "$value_$i";
    }
0

3 Answers 3

2

Instead of naming variables like you did, there's something called an array.

Instead of having :

$value_0 = "0"; 
$value_1 = "1";
$value_2 = "2"; 

you'd have:

$value[0] = "0";
$value[1] = "1";
$value[2] = "2";

Since you're new to PHP, you should start using tools that PHP gives you. You wanted to iterate your variables by utilizing a numerical index - which is fine. The issue lies in naming your variables.

An array lends you a hand here, it's a way of referencing multiple variables under the same name.

If you haven't read or heard about it, head on to PHP documentation page about arrays.

Using arrays, your code would look like this:

$value[0] = "0";
$value[1] = "1";
$value[2] = "2";
$nr = 2;

for ($i=0; $i <= $nr; $i++)
{
    echo $value[$i];
}
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$value_0 = 0;
$value_1 = 1;
$value_2 = 2; 
$nr = 2;
    for ($i=0; $i <= $nr; $i++)
    {
        echo ${"value_" . $i};
        echo '<br>';
    }
?>

Wrap them in {}

Comments

0

You can have this simply like this

    echo ${value_.$i};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.