note 16035 added to ref.var
| From: | php-general at lists dot php dot net | Date: | Sat, 13 Oct 2001 16:55:29 +0000 |
| Subject: | note 16035 added to ref.var | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-18881@lists.php.net to get a copy of this message | ||
Assigning names to variables dynamically (using variables when assigning names to variables).
In PHP you can easily set a name for a new variable using another variable. This is done simply by
stating the second var as the varname like this: $$varname (notice the double $$)
This is very elegant.
Here is an example:
for ($i = 1; $i <= 7; $i++) {
$varname = "txt_"."$i";
$$vn="nr."."$i";
}
print("$txt_1, $txt_4, $txt_5, $txt_7");
will output: "Nr. 1, Nr. 4, Nr. 5, Nr. 7"
You can use this for example to query a database in a for-loop and assigning the result to a uniqe
var in each run like this:
for ($i = 1; $i <= 7; $i++) {
$result = mysql_query("SELECT FROM table_name WHERE field_name LIKE '$i'");
while ($row = mysql_fetch_array($result)) {
extract($row);
$varname = "result_"."$i";
$$varname="$field_name";
} //while-loop ending
} // for-loop ending
--
http://www.php.net/manual/en/ref.var.php
http://master.php.net/manage/user-notes.php?action=edit+16035
http://master.php.net/manage/user-notes.php?action=delete+16035
http://master.php.net/manage/user-notes.php?action=reject+16035