Dram Dram - 7 months ago 11
PHP Question

It's possible to increment a declaration of a variable?

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

Answer

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];
}