Programmatically create variables

Asked

Viewed 85 times

1

There is the possibility to create variables programmatically?

Example (this example does not work, it is only to understand the idea):

I want to create the variables: $var0,$var1,$var2,$var3 and print your name and value.

$qtdVariaveis = 5;
$prefixo = 'var';
$valorPadrao = 10;

for ($c = 0; $c < 5; $c++) {

    echo $prefixo . $c = $valorPadrao;
}

Desired exit:

$var0 = 10
$var1 = 10
$var2 = 10
$var3 = 10
  • Would that be ${$prefixo . $c} = $valorPadrao;?

  • @Valdeirpsr yes, only the name of the variable had to be printed. There is this function ?

  • 1

    It’s the same thing.echo ${$prefixo . $c}

1 answer

3


There is a but should not do, has no reason to do this.

Use a array and be happy. Be it with sequential numeric index, be it an associative with the whole name.

  • 2

    Although the question is duplicated, this answer is practically the only true one. The very rare exceptions only happen in the hands of those who already understand very well the language and the mechanism, which in PHP is white fly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.