Creating variable names from an array list

How can I dynamically create variable names based on an array? I mean, I want to skip this array using foreach and create a new variable $elem1, $otheretc. Is it 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
}
+3
source share
4 answers
foreach ($myarray as $name) {
   $$name = 1;
}

This will create the variables, but they will only be visible in the loop foreach. Thank you Jan Hancic for this.

+3
source

The goreSplatter method works, and you should use it if you really need it, but here is an alternative only for hits:

extract(array_flip($myarray));

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

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

Wildly rewarding.

+3

-

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

Extract ( $myVars );

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

+2
source

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

0
source

Source: https://habr.com/ru/post/1783226/


All Articles