note 16690 added to control-structures.foreach

From: Date: Fri, 09 Nov 2001 04:47:08 +0000
Subject: note 16690 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-20625@lists.php.net to get a copy of this message
This may be obvious to some, but not to others. You can use the $$ feature of the language combined with foreach to loop through the $HTTP_GET_VARS and $HTTP_POST_VARS arrays to quickly create an individual variable for each element. One line of code does the trick foreach($HTTP_POST_VARS as $key => $value) {$$key = $value;} if the post array had the following elements: foo=x bar=y then you would end up with variables $foo = "x" and $bar = "y" This is also useful for pulling info from databases in a flexible fashion. $sql = "statement that retrieves one row of data"; $result = mysql_query($sql) or die ("Query invalid"); $row = mysql_fetch_row($result); foreach($row as $key => $value) { $a = mysql_field_name($result,$key); $$a = $value; } If your table contains four columns col1, col2, col3, and col4, then when the loop is done you'll have four variables $col1 = data in col1 $col2 = data in col2 $col3 = data in col3 $col4 = data in col4 Hopefully someone will find this useful. -- http://www.php.net/manual/en/control-structures.foreach.php http://master.php.net/manage/user-notes.php?action=edit+16690 http://master.php.net/manage/user-notes.php?action=delete+16690 http://master.php.net/manage/user-notes.php?action=reject+16690

« previous php.notes (#20625) next »