--- James Keeline <[EMAIL PROTECTED]> wrote:

> --- Pete <[EMAIL PROTECTED]> wrote:
> 
> > 
> > I know that I can do:
> > foreach ( $_POST as $key => $value ) {
> >  print $key . " = " . $value . "<BR/>";
> > }
> > 
> > but is there a way to load the variables with the values, to save 
> > $this=$_POST['this'];
> > $that=$_POST['that'];
> > $the_other=$_POST['the_other'];
> > 
> > -- 
> > Pete Clark
> 
> PHP has a function for nearly everything:
> 
> http://php.net/extract
> 
> in this case:
> 
> extract($_POST);
> 
> Keep in mind that this is barely better than having register_globals ON.  It
> is
> sometimes better to set all of the variables you expect from the POST input
> to
> some empty value and use the EXTR_IF_EXISTS flag with extract:
> 
> $firstname=$lastname=$email=$comment="";
> extract($_POST, EXTR_IF_EXISTS);
> 
> Then, if someone tries to add other variables to your application, especially
> in an attempt to overwrite key variables you might use for logged in status,
> etc., only the variables which are already set will be transformed by
> extract()
> into local variables.
> 
> Naturally, extract() should be called at the top of your program to prevent
> overwriting values as well.
> 
> James
> http://www.ITeachPHP.com

By the way, if you wanted to keep the foreach loop, the trick is to use the $$
or variable-variable:

foreach ( $_POST as $key => $value ) 
{
 $$key = $value;
}

This says:  take the value of the variable $key and treat that value as the
name of a variable.  In this case we are setting it with the value in $value.

It's a useful technique though extract() is certainly morre concise.  I also
use extract() after a mysql_fetch_assoc() since it returns an associative array
with field names and values.

James



Community email addresses:
  Post message: [email protected]
  Subscribe:    [EMAIL PROTECTED]
  Unsubscribe:  [EMAIL PROTECTED]
  List owner:   [EMAIL PROTECTED]

Shortcut URL to this page:
  http://groups.yahoo.com/group/php-list 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/php-list/

<*> To unsubscribe from this group, send an email to:
    [EMAIL PROTECTED]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 


Reply via email to