3

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
}
2
  • Why do you want to create this variables (dynamically)? What do you want to achieve in the end? Although it is possible to do so, in most cases it is not necessary and makes your code more complex. Commented Jan 3, 2011 at 13:55
  • It's not an array list in PHP - it's just an array. Commented Jan 3, 2011 at 13:56

4 Answers 4

4
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.

Sign up to request clarification or add additional context in comments.

4 Comments

This will create local variables unusable outside of the foreach loop, won't it?
@Jan A good argument. +1 for your answer then. I updated my answer.
foreach does not create a local scope.
Well I'll be darned, I was programming all this time under the impression that it does :) Seems logical that it would create them in the local scope.
3

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.

Comments

2

Something like this should do the trick

$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
  $myVars[$arr] = 1;
}

Extract ( $myVars );

What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).

Comments

0

Use array_keys($array)

i.e.

$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');

$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
  $myarray[$singleKeyName] = 1;
}

http://www.php.net/manual/en/function.array-keys.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.