note 16035 deleted from ref.var by jimw

From: Date: Sat, 13 Oct 2001 19:43:30 +0000
Subject: note 16035 deleted from ref.var by jimw
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-18890@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

« previous php.notes (#18890) next »