extract(); – Very useful indeed…

Pulling in $_POST or $_GET variables can be quite a pain sometimes, enter a handy built-in PHP function: extract() Let’s pretend your making a contact form, that when a user clicks submit goes to “process_contact.php” That would mean that your query string would look something like this: process_contact.php?name=Some%20Visitor& email=&message=Hello%20World Typically you would have to do [...]

Pulling in $_POST or $_GET variables can be quite a pain sometimes, enter a handy built-in PHP function: extract()

Let’s pretend your making a contact form, that when a user clicks submit goes to “process_contact.php” That would mean that your query string would look something like this:

process_contact.php?name=Some%20Visitor&
email=&message=Hello%20World

Typically you would have to do the following:

$name = $_GET['name'];
$email = $_GET['email'];
$message= $_GET['message'];

That’s not bad for just three items but what if it was an online survey and you wanted to gather all the $_GET data from that? Wouldn’t it be nice if PHP could automate it for you?

It can. With 1 (yes that’s right 1) line of code.

extract($_GET, EXTR_PREFIX_SAME, "var");

That function, which is a built-in PHP function by the way is extracting all the query string variables (in our case: name, email & message) and setting them equal to their respective values (in our case: Some Visitor, , Hello World)
So to access those variables we just do this:

echo $name;
echo $email;
echo $message;

The EXTR_PREFIX_SAME is basically saying if Joe Programmer has already made a variable called $name (or any other that would exactly match one from the query string) Then we are going to prefix it with “var”

Here is an example:

$name = Tom;
extract($_GET, EXTR_PREFIX_SAME, "var");
echo "This is the name we declared--->".$name."
";
echo "This is the name from query string--->".$var_name."
";

And one last cool thing about extract(); It will work with ANY array.
Example:

$test = array ('label1' => 1, 'label2' => 2);

extract($test, EXTR_PREFIX_SAME, "var");

echo "Label1 --->" .$label1."
";
echo "Label2 --->" .$label2."
";

How sweet is that? Enjoy.

For more info about extract(); be sure to check out the manual (www.php.net)