Dynamic Variables in PHP

Almost Five years I was use PHP as my Web Server Scripting Languange for my Web Application, from simple application until more robust application. And like other Web Server Scripting Languange, there are some variables function that really useful to make my PHP code more usable and easy to understand, one of my favorites is dynamic variables.

How to use dynamic variables in PHP? use my simple tutorial.
Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:

$var = "hello";
Now let’s say you want a variable whose name is the value of the $var variable. You can do that like this:

$$var = "World";

PHP parses $$var by first dereferencing the innermost variable, meaning that $var becomes “hello”. The expression that’s left is $”hello”, which is just $hello. In other words, we have just created a new variable named hello and assigned it the value “World”. You can nest dynamic variables to an infinite level in PHP, although once you get beyond two levels, it can be very confusing for someone who is trying to read your code.

There is a special syntax for using dynamic variables, and any other complex variable, inside quoted strings in PHP:

echo "Hello ${$var}";

This syntax also helps resolve an ambiguity that occurs when variable arrays are used. Something like $$var[1] is ambiguous because it is impossible for PHP to know which level to apply the array index to. ${$var[1]} tells PHP to dereference the inner level first and apply the array index to the result before dereferencing the outer level. ${$var}[1], on the other hand, tells PHP to apply the index to the outer level.

Initially, dynamic variables may not seem that useful, but there are times when they can shorten the amount of code you need to write to perform certain tasks. For example, say you have an associative array that looks like:

$array["abc"] = "Hello";
$array["def"] = "World";

Associative arrays like this are returned by various functions in the PHP modules. mysql_fetch_array() is one example. The indices in the array usually refer to fields or entity names within the context of the module you are working with. It’s handy to turn these entity names into real PHP variables, so you can refer to them as simply $abc and $def. This is done as follows:

foreach($array as $index=>$value) {
$$index = $value;
}

18 thoughts on “Dynamic Variables in PHP

  1. The dynamic variables can be used to create a dynamic url.
    If you have spare time, please share also how to create dynamic url
    Thank you

  2. Here is my example if you find it handy
    $query = “Select id_codeset,cs_display FROM codeset”;
    $result = mysql_query($query);
    $num_rows=mysql_num_rows($result);

    while($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
    $cs_display = $row[“cs_display”];
    $$cs_display = $row[“id_codeset”];

    }

    The above simply loads a codeset table with eg. $country (display) 5 (codeset) $state (display) 6 (codeset) $city (display) 8 (codeset)
    you get the hint.
    Now if I want to query all my countries or states , etc I simply say for example Select * from codevalue where codeset = $country

    real neat and handy for populating forms in a readable manner

  3. Hi
    I just read your article. It was managed so good. I could fully understand it, in a short time. So, I thought to write an message to thank you.

    I wish happiness for you
    Pooya, from I. R. Iran

  4. suppose your variable names are

    $v1=2;
    $v2=3;
    …
    .
    .
    $v100=100;
    then you can show through loop
    for($i=1;$i<1=100;$i++)
    {
    $y="v".$i;
    echo $$y;
    }
    if you want to use this concept in query the write
    or($i=1;$i<1=100;$i++)
    {
    $y="v".$i;
    $y=$$y;
    }
  5. Thankyou for this! I was hunting google for some way on how to do this. I wanted to output the month date(M) as $Feb or $Mar etc. In a drop-down menu, I had: echo $Feb >February etc… now I can set $$month = ‘SELECTED’ and have my drop-down list reflect the current month instead of writing a whole bunch of ‘if’ statements!

  6. Hey Nurudin Jauhari.

    I have a quick question is it possible to use something similar for dynamic $_SESSION variable

    Your help will be greatly appreciated
    Antonio

  7. Ya, bermanfaat banget saat ambil data dari GET/POST/COOKIE, misal

    $fields = explode(‘,’, ‘name,email,homepage,comment’);
    foreach($fields as $field) {
    $$field = isset($_POST[$field]) ? $_POST[$field] : ”;
    }

    untuk pakai tinggal

    echo “$name, $email, $homepage, $comment”;

    register global off tapi on – atau gimana yah? au ah gelap

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>