Page 1 of 1

Getting the variable name from an array

Posted: Fri Apr 06, 2012 10:15 pm
by rsphorler
I'm trying to get the variable name from an array of 9 MySQL variables to look at.

The code is

Code: Select all

$result2 = @mysql_query("SELECT maxsize, badge FROM classes where maxsize>0");	
	while($row = mysql_fetch_array( $result2 )) {	
	$maxsize = $row['maxsize'];
	$badge = $row['badge'];
 	$stored_values = array($class1,$class2,$class3,$class4,$class5,$class6,$class7,$class8,$class9);
		for ($i = 0; $i <= 9; $i++) {
			if($badge==$stored_values[$i]) {
			$checkmessage="Scout has chosen a class ($stored_values[$i]) with a max class size of $maxsize";
			}
		}		
	}	
I'm using this so I can determine what the class was (i.e. the value of $class#) initially I had a long IF statement but that would not allow me to determine which of the 9 classes matched (i.e. the class time) or what that actual class was (e.g. Camping). Now I want to be able to do a second query by finding out which of the array variables it was so I can get this code to work:

Code: Select all

$result3 = @mysql_query("SELECT * FROM classes where <<CLASS#>> = $stored_values[$i])");	
The problem is <<CLASS#>> what should I replace this with to get class1 or class 2 or ....... that produced the match in the first place.

Hopefully that makessense and someone can give me the probably very simple code to do it

Richard

Re: Getting the variable name from an array

Posted: Sat Apr 07, 2012 2:23 am
by azycraze
try this

Code: Select all

$stored_values = array($class1,$class2,$class3,$class4,$class5,$class6,$class7,$class8,$class9);
$result2 = @mysql_query("SELECT maxsize, badge FROM classes where maxsize>0");  
        while($row = mysql_fetch_array( $result2 ))
        {   
        $maxsize = $row['maxsize'];
        $badge = $row['badge'];
        $n=array_search($badge,$stored_values);
                   if($n != NULL )
                       {
                        $checkmessage="Scout has chosen a class ($stored_values[$n]) with a max class size of $maxsize";   
                       }        
        }  
will work sometimes