Monday, October 21, 2013

Convert Key => Value Arrays Into Standard Variables In PHP

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.