[php] Using braces with dynamic variable names in PHP

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.

This question is related to php variables dynamic dynamic-variables

The answer is


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];


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;
}

Try using {} instead of ():

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

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.


Try using {} instead of ():

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

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

$r = (object) $MyQueryResult;
echo $r->key;

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']()

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?

Examples related to dynamic-variables

Using braces with dynamic variable names in PHP Assigning variables with dynamic names in Java Use dynamic variable names in JavaScript