228

I'm trying to use dynamic variable names (I'm not sure what they're actually called) But pretty much like this:

for($i=0; $i<=2; $i++) {
    $("file" . $i) = file($filelist[$i]);
}

var_dump($file0);

The return is null which tells me it's not working. I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research. $filelist is defined earlier on.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
user1159454
  • 3,267
  • 3
  • 19
  • 25
  • 27
    **Don't**! There is never a good reason to use them. They are, effectively, just an untidy array. Use a proper array instead. – Quentin Feb 13 '12 at 08:37
  • Alright I'm sorry, I just went back and picked an answer for each question I've asked so far. Good thing it's only 7 :P – user1159454 Feb 13 '12 at 08:56
  • 3
    And Quentin, why are they bad practice?? There must be a reason they exist alongside arrays I'd think – user1159454 Feb 13 '12 at 08:57
  • 2
    @user1159454 — They are a disorganised mess without all the tools that can be applied to arrays available to them. They exist for ancient legacy reasons and crazy edge cases. – Quentin Feb 13 '12 at 11:20
  • 9
    Crazy edge cases may be exactly why someone would want to ask this question. – Vincent Nov 06 '14 at 19:50
  • Here is an example http://thegeekyland.blogspot.com/2015/11/php-dynamic-variables.html – Arlind Hajredinaj Dec 02 '15 at 19:13
  • Debugging, understanding and bug fixing of such code can become a nightmare. – martinstoeckli Mar 03 '16 at 12:59
  • Careful if you are using it on $_POST or $_GET to put the parameters into variables through a loop. Someone could maliciously (or accidentally) overwrite existing variables. – David Wylie Jun 02 '16 at 12:13
  • Thanks folks. I searched for the question as I was thinking that ${} was the right way to go for an array of values I'm building from a database. But your comments made me reevaluate my "design" choices and I'm simply updating a multidimensional associative array with the results from the database query (it's a long list of attributes) rather that storing each result in a separate dynamically created variable. – MuppetDance Mar 06 '22 at 17:03

9 Answers9

591

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working Example


Using ${} is a way to create dynamic variables, simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 6
    Is it also possible to create dynamic arrays with the same logic? – dtakis Sep 16 '13 at 13:20
  • I have the same doubt of @dtakis, can you help us? If possible, please take a look at [this question](http://stackoverflow.com/questions/24591687/php-method-to-get-values-dynamically-from-an-array-object-property). – Marcio Mazzucato Jul 06 '14 at 00:54
  • Jut a warning if you are using this to include a variable (the most useful way IMHO) don't forget to use double quotes. `${'fixedTime$i'} = $row['timeInstance'];` gives you a not very useful `$fixedTime$i` instead of `$fixedTime1, $fixedTime2` etc. (Fortunately spotted it almost straight away.) – BeNice Jan 27 '16 at 05:13
113

Overview

In PHP, you can just put an extra $ in front of a variable to make it a dynamic variable :

$$variableName = $value;

While I wouldn't recommend it, you could even chain this behavior :

$$$$$$$$DoNotTryThisAtHomeKids = $value;

You can but are not forced to put $variableName between {} :

${$variableName} = $value;

Using {} is only mandatory when the name of your variable is itself a composition of multiple values, like this :

${$variableNamePart1 . $variableNamePart2} = $value;

It is nevertheless recommended to always use {}, because it's more readable.

Differences between PHP5 and PHP7

Another reason to always use {}, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.

In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.

Case 1 : $$foo['bar']['baz']

  • PHP5 interpetation : ${$foo['bar']['baz']}
  • PHP7 interpetation : ${$foo}['bar']['baz']

Case 2 : $foo->$bar['baz']

  • PHP5 interpetation : $foo->{$bar['baz']}
  • PHP7 interpetation : $foo->{$bar}['baz']

Case 3 : $foo->$bar['baz']()

  • PHP5 interpetation : $foo->{$bar['baz']}()
  • PHP7 interpetation : $foo->{$bar}['baz']()

Case 4 : Foo::$bar['baz']()

  • PHP5 interpetation : Foo::{$bar['baz']}()
  • PHP7 interpetation : Foo::{$bar}['baz']()
John Slegers
  • 45,213
  • 22
  • 199
  • 169
22

Try using {} instead of ():

${"file".$i} = file($filelist[$i]);
Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
  • 1
    from phpNET manual http://php.net/manual/ru/language.variables.variable.php `$price_for_monday = 10; $price_for_tuesday = 20; $today = 'tuesday'; $price_for_today = ${ 'price_for_' . $today}; echo $price_for_today; // will return 20 ` – Vladimir Ch Apr 20 '18 at 21:08
8

I do this quite often on results returned from a query..

e.g.

// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)
{
   ${$key}=$value;
}

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

Tom
  • 81
  • 1
  • 1
3

Tom if you have existing array you can convert that array to object and use it like this:

$r = (object) $MyQueryResult;
echo $r->key;
corysus
  • 647
  • 9
  • 12
3

Try using {} instead of ():

${"file".$i} = file($filelist[$i]);
Vildan Bina
  • 309
  • 3
  • 11
1

i have a solution for dynamically created variable value and combined all value in a variable.

if($_SERVER['REQUEST_METHOD']=='POST'){
    $r=0;
    for($i=1; $i<=4; $i++){
        $a = $_POST['a'.$i];
        $r .= $a;
    }
    echo $r;
}
Murad
  • 11
  • 2
0

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

Community
  • 1
  • 1
M61Vulcan
  • 337
  • 3
  • 7
0

After trying all the mentioned above, it worked the simple way: It's accessed as $_POST variable, as it comes directly out of a dynamic form.

$variableName= "field_".$id;
echo $_POST[$variableName];