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=visitor@domain.com&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.
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, visitor@domain.com, Hello World)
So to access those variables we just do this:
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:
And one last cool thing about extract(); It will work with ANY array.
Example:
How sweet is that? Enjoy.
For more info about extract(); be sure to check out the manual (www.php.net)
January 22nd, 2007 at 1:39 pm
Really nice use of the command Extract.
Thanks