Create variables with an array dynamically

2

Dynamically declare variables

for($i = 0; $i < 10 ; $i++)
{   
    $arry[$i]= "var" .$i;
    echo $arry[$i] . "<br>";
    $$arry[$i] = "ok";  //<-Aqui queria que a variavel $var'i' = "ok"
}

 echo $var0
    
asked by anonymous 06.03.2017 / 21:33

1 answer

4

To transform elements of an array into variables use the function extract() , if there are too many elements it does not make much sense to use.

It is recommended to pass as an argument the EXTR_SKIP option, which prevents that a variable with that name already exists has its value overwritten.

for($i=0; $i<10; $i++){
    $arr['var'.$i] = 'ok '. rand(1,99);
}

extract($arr, EXTR_SKIP);

Another way to set a prefix on variables is to use the EXTR_PREFIX_ALL option so each element will have the entered name followed by an underline. In this examples the names will be $var_0 , $var_1 etc

for($i=0; $i<10; $i++){
    $arr[$i] = 'var'.$i;
}

extract($arr, EXTR_SKIP|EXTR_PREFIX_ALL, 'var');

You can see the variables created in running the script like this:

echo "<pre>";
print_r(get_defined_vars());

Recommended reading:

Manual - extract

Manual - get_defined_vars

    
06.03.2017 / 21:50