note 26101 added to language.variables.variable

From: Date: Fri, 18 Oct 2002 01:22:21 +0000
Subject: note 26101 added to language.variables.variable
Groups: php.notes 
Request: Send a blank email to php-notes+get-38227@lists.php.net to get a copy of this message
I needed to dynamically evaluate a varible.... i wanted to create the name of the variable on the fly and then get it's value. In other words, I wanted to dynamically build the name of a variable, and then evaluate it. Example: These items already exists: $var1 = "bird"; $var2 = "cat"; $var3 = "dog"; ... let's say there are 3 million of these variables in a series... Now i want to find out which var has a value of "dog" - so i need to dynamically build the name of the variable. You can do the FOR loop thing to create a string that represents the name of the variable, but how on earth do you evaluate a string as if it were a variable? enter "variable variables" for ($i=0; $i<4; $i++){ //create the label of the variable; $var_label_string = "var$i"; //Now evaluate that string as if it were a variable !; $value_of_that_var = ${$var_label_string}; //now find out if that var is equal to "dog"; if ($value_of_that_var == "dog"){ print "Dog found here: $var_label_string"; } } -- http://www.php.net/manual/en/language.variables.variable.php http://master.php.net/manage/user-notes.php?action=edit+26101 http://master.php.net/manage/user-notes.php?action=delete+26101 http://master.php.net/manage/user-notes.php?action=reject+26101

« previous php.notes (#38227) next »