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


Subscribe to Full RSS Feed

RSS FeedIf you thing this article useful, please consider subscribing to our RSS Feed or e-mail updates and stay updated with us. You can also follow @JauhariNET on twitter for latest updates.


About Jauhari

This is me Nurudin Jauhari. Just human like you, I come from Gunungkidul, small place at Yogyakarta, and Today I live at Malang I was born 30/04/1980 in Ponjong, small village in Gunungkidul, Almost my time in 1 - 15 Years stay at this Village. More

This entry was posted in PHP and tagged , , , , , .
Bookmark the permalink.



18 Responses to Dynamic Variables in PHP

  1. Ramzi says:

    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. ray ban says:

    from simple application until more robust application. And like other Web Server Scripting Languange

  3. Reminds me of my days in college trying to learn Web Server Scripting Language and being bored out of my head.

  4. and add says:

    thanks.but i don’t know PHP

  5. ray ban says:

    Your help will be greatly appreciated
    Antonio

  6. Pingback: How to Inherit from Multiple Objects (Workaround) | Server-Side Magazine

  7. Ken says:

    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

  8. Guide to Get says:

    Dynamic Variables in PHP – this topic is level 3 for me who just learn level 1, but thanks for sharing.:D

  9. baby hats says:

    Dynamic Variables= Names of Variables are Variables too!!

  10. from simple application until more robust application. And like other Web Server Scripting Languange

  11. Pooya Fani says:

    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

  12. nanhe kumar says:

    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;
    }
  13. Steve says:

    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!

  14. Antonio says:

    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

  15. Tim says:

    This is the same text as in The PHP Pocket Reference from Oreilly.
    http://www.oreilly.com/catalog/phppr/chapter/php_pkt.html

  16. elle says:

    Thank you.
    That is a big help :)

  17. ferdhie says:

    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>