Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating variable names from an array list

Tags:

arrays

php

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?

$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
    //create a new variable called $elem1 (or $other or $elemother, etc.) 
    //and assign it some default value 1
}
like image 426
silow Avatar asked Dec 07 '25 20:12

silow


2 Answers

foreach ($myarray as $name) {
   $$name = 1;
}

This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.

like image 150
Linus Kleen Avatar answered Dec 10 '25 10:12

Linus Kleen


goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:

extract(array_flip($myarray));

This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:

echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'

Wildly useful.

like image 25
Tatu Ulmanen Avatar answered Dec 10 '25 10:12

Tatu Ulmanen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!