extract(); - Very useful indeed…

Posted by justinjohnson on May 3rd, 2005

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:

PHP:
  1. process_contact.php?name=Some%20Visitor&
  2. email=visitor@domain.com&message=Hello%20World

Typically you would have to do the following:

PHP:
  1. $name = $_GET['name'];
  2. $email = $_GET['email'];
  3. $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.

PHP:
  1. 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, visitor@domain.com, Hello World)
So to access those variables we just do this:

PHP:
  1. echo $name;
  2. echo $email;
  3. 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:

PHP:
  1. $name = Tom;
  2. extract($_GET, EXTR_PREFIX_SAME, "var");
  3. echo "This is the name we declared--->".$name."
  4. ";
  5. echo "This is the name from query string--->".$var_name."
  6. ";

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

PHP:
  1. $test = array ('label1' => 1, 'label2' => 2);
  2.  
  3. extract($test, EXTR_PREFIX_SAME, "var");
  4.  
  5. echo "Label1 --->" .$label1."
  6. ";
  7. echo "Label2 --->" .$label2."
  8. ";

How sweet is that? Enjoy.

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

One Response

  1. Leandro Ardissone Says:

    Really nice use of the command Extract.

    Thanks

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Advertisements

Recent Posts

Categories

Archives

Meta: