Getting the variable name from an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rsphorler
Forum Newbie
Posts: 1
Joined: Fri Apr 06, 2012 10:06 pm

Getting the variable name from an array

Post 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
User avatar
azycraze
Forum Commoner
Posts: 56
Joined: Mon Oct 24, 2011 12:08 pm
Location: India

Re: Getting the variable name from an array

Post 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
Post Reply