May 3, 2005 Code, Web Dev
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:
| 1 |
|
| 2 | process_contact.php?name=Some%20Visitor&
|
| 3 | email=visitor@domain.com&message=Hello%20World
|
| 4 | |
Typically you would have to do the following:
| 1 |
|
| 2 | $name = $_GET['name'];
|
| 3 | $email = $_GET['email'];
|
| 4 | $message= $_GET['message'];
|
| 5 | |
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.
| 1 |
|
| 2 | extract($_GET, EXTR_PREFIX_SAME, "var");
|
| 3 | |
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:
| 1 |
|
| 2 | echo $name;
|
| 3 | echo $email;
|
| 4 | echo $message;
|
| 5 | |
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:
| 1 |
|
| 2 | $name = Tom;
|
| 3 | extract($_GET, EXTR_PREFIX_SAME, "var");
|
| 4 | echo "This is the name we declared--->".$name."
|
| 5 | ";
|
| 6 | echo "This is the name from query string--->".$var_name."
|
| 7 | ";
|
| 8 | |
And one last cool thing about extract(); It will work with ANY array.
Example:
| 01 |
|
| 02 | $test = array ('label1' => 1, 'label2' => 2);
|
| 03 | |
| 04 | extract($test, EXTR_PREFIX_SAME, "var");
|
| 05 | |
| 06 | echo "Label1 --->" .$label1."
|
| 07 | ";
|
| 08 | echo "Label2 --->" .$label2."
|
| 09 | ";
|
| 10 | |
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
Thanks
December 5th, 2009 at 9:18 pm