Create variables with a dynamically shaped array

Asked

Viewed 1,012 times

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

1 answer

4


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

It is recommended to pass the option as argument EXTR_SKIP this prevents that if a variable with this 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 option EXTR_PREFIX_ALL so each element will have the name given followed by an underline. In these 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 the script execution this way:

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

Recommended reading:

Manual - Extract

Manual - get_defined_vars

Browser other questions tagged

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