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
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
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:
Browser other questions tagged php
You are not signed in. Login or sign up in order to post.