Convert Key => Value Arrays Into Standard Variables In PHP

By  on  

I don't mind using arrays -- in fact, I love them. They're easy to use and hold collections of information well.

I don't always want to use arrays though. Why use:

echo $user['first_name'];

when you could simply use:

echo $first_name;

So how can we get rid of the array part of the variables?

The Code

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

//or....

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

A few variables you must be careful with are:

  • $_GET
  • $_POST
  • $_REQUEST

Why? Because $_GET, $_POST, and $_REQUEST variables can manipulated by the user and that would present a huge security concern.

Recent Features

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

  • By
    MooTools Equal Heights Plugin:  Equalizer

    Keeping equal heights between elements within the same container can be hugely important for the sake of a pretty page. Unfortunately sometimes keeping columns the same height can't be done with CSS -- you need a little help from your JavaScript friends. Well...now you're...

  • By
    Facebook-Style Modal Box Using MooTools

    In my oh-so-humble opinion, Facebook's Modal box is the best modal box around. It's lightweight, subtle, and very stylish. I've taken Facebook's imagery and CSS and combined it with MooTools' awesome functionality to duplicate the effect. The Imagery Facebook uses a funky sprite for their modal...

Discussion

  1. Interesting effect, but it has the same effect of php’s extract function! In your example, you can do extract($user); and so call $first_name; ;)

    http://www.php.net/extract

  2. Good point Hugo. My post wasn’t detailed enough, or perhaps was over-simplified.

    With the loop, you can do special operations to the values. For example:

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

    …removes slashes.

    • Thanks for this little simple snip of code. I have spent hours trying to get a query to read a
      WHERE id = "'.$_POST(var).'" Everything I tried would echo an array and then the value which the query just would say da~ha what??? After using this line above and the WHERE id = "'.$key.'" it work perfect as designed.Thank You for taking the time to make your post.

  3. Peter Scarborough

    I have used this alot for both GET’s and POST’s, sure, they can create their own variables, who cares? If I use a variable, I always declare it after pulling from get or post, the variables that I use from post and get are also validated for correct values.

    Also, something I have found handy for dealing with case sensitivity for get variables, (since sometimes if someone posts it to say, ICQ for someone else to visit, ICQ will lowercase the whole string) is

    foreach($_GET as $k = $v) {
    $k = strtolower($k);
    \$$k = $v
    }
    

    then you can safely test to see if the get was set

    if(isset($variablenametotestfor)) {//begin execution}
    
  4. Thank you for the RegEx, Peter — that could prove very useful!

  5. Peter Scarborough

    Sorry, there was an error in my regex syntax there, I learned regex with javascript, and just learning PHP regEx… I got the two confused when I wrote that

    The correct syntax for the above would be

    $acceptedGETS = "/\bvarname1\b|\bvarname2\b|\bvarname3\b|\betc\b/";
    foreach($_GET as $key => $value) {
    $key = strtolower($key);
    if (preg_match($acceptedGETS,$key)) $$key = $value;
    }
    

    the \b is required on both sides of each variable name to force exact words, without them qvarname1x34r would match.

  6. Hey is not on google so I was wondering what the ${ } does? I have never seen it before.

  7. Hi David,

    I think the brackets are just a way of delimiting the variable’s name from the rest of the string.

    Say you had variable $table_prefix,

    echo “table name: $table_prefix_users”; // would return “table name: “;
    echo “table name: ${table_prefix}_users”; // would return “table name: wp_users”;

    I am not sure about this :) I am most likely wrong.

    Cheers!
    Droope

  8. No, Droope is correct. Mostly.

    The ${ } does designate a string.

    But the purpose of this article is showing how to easily assign array variables to their key name. I know that sounds confusing, but its it.

    Example:

    $people[‘me’] = ‘robert’;
    $people[‘friend’] = ‘sam’;
    $people[‘girl’] = ‘bailey’;

    foreach($people as $key => $val) {
    // ${“me”} = ‘robert’

    ${$key} = $val; //or $$key = $val;
    }

    So that

    echo $me; //echo “robert”;

  9. (great blog, btw)

  10. Pascal

    As Hugo Magalhães said, I think this woud be a “better” solution…
    This way, nobody can modify or change your variables!

    extract($REQUEST, EXTR_PREFIX_ALL, "my_prefix");

  11. Zync

    Thank you all very much for this, was exactly what I was looking for today. using Peter’s approach just whipped up a quick match string, just add your allowed variables to the array.

    $acceptedIncomingVars = array('id', 'name', 'code', 'cost', 'desc', 'mixtypeid', 'mixdetailid');
    
    $acceptedVars = "/";
    for($i = 0; $i  $value) {
        $key = strtolower($key);
    
        if (preg_match($acceptedVars,$key))
        {
            $$key = $value;
        }
    }
    
    echo $code;
    
  12. Would you be able to help me get this problem sorted.

    I have this

    $choices = array($_GET['choices']);
    

    which returns this:

    1,2,3,4,5

    I need to be able to go through them and not only the value of the items to the variable name but also as the value.

    So ideally I would like this:

    $choice1 = "1";
    $choice2 = "2";
    $choice3 = "3";
    etc..
    

    and for instance if

    $choices = array($_GET['choices']);
    

    returned :

    1,3,6,8

    I would like

    $choice1 = "1";
    $choice3 = "3";
    $choice6 = "6";
    $choice8 = "8";
    etc..
    

    Thank you.

  13. Nice, trick and thank to first comment about extract function :)

  14. Sachin

    Dear,

    PHP 5 is already resolved the issue by creating a function called “extract()” which do the same thing as per by the above foreach loop.

  15. Sachin

    use function extract() to get rid of all this stuff.

  16. briedis

    This is super ugly/bad! Now people use IDE`s, and this makes life damn hard, because you can’t see what variables are defined etc.

    The only place where this could be used, is when you render a view, which uses global variables and output buffering.

    Otherwise, making all evil data that user submits as variables sounds veeeery uncool.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!