Retain state in dropdown list

Whenever I have to deal with retaining state in my dropdown lists, my results seem to be hit and miss. In this example, I am making a form that takes the hex code of a colour, converts it to rgb code and displays a sample of the colour. (Just for fun and practice). I have used an array and nested ‘for’ loops to generate the six dropdown lists for the hex code. It won’t retain state. Could someone please just take a look and see why it doesn’t work? Thank you.

	$hex_array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f);
	for ($i=1; $i<=6; $i++) {
	     $hex_digit = "digit" . $i;
	     print("<select name=\\"$hex_digit\\">");
	
 	     for ($j=0; $j<16; $j++) {
			if ($hex_digit == $j) {
				$selected = "selected=\\"selected\\" ";
			} else {
				$selected = "";
			}
			print("<option value=\\"$j\\" $selected>$hex_array[$j]</option>");
	     }
	
             print("</select> ");
	}

Hello,

$hex_digit = "digit" . $i; 

$hex_digit contains always “digit” and something, therefore, when you compare value of $hex_digit with $j then it is always FALSE, therefore, the variable $selected never contains “selected=\”$hex_digit\“>”.

Changed code here:

if ($hex_digit == 'digit'.$j) {
	$selected = "selected=\\"selected\\" ";
} else {
	$selected = "";
}

The lesson is that when faced with a conditional check which does not seem to behave always “var_dump()” the variables onto the page and look at the HTML source code if you cannot see the values dumped out. Don’t echo them, var_dump() them so you see what type they are and what value they contain.


    $hex_array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f); 
    for ($i=1; $i<=6; $i++) { 
         $hex_digit = "digit" . $i; 
         print("<select name=\\"$hex_digit\\">"); 
     

          for ($j=0; $j<16; $j++) { 


// debug - uncomment the lines below

var_dump($hex_digit);
var_dump($j);


// your conditional check is here, if()

            if ($hex_digit == $j) { 
                $selected = "selected=\\"selected\\" "; 
            } else { 
                $selected = ""; 
            } 
            print("<option value=\\"$j\\" $selected>$hex_array[$j]</option>"); 
         } 
             
             print("</select> "); 
    }   

I am not detracting from jakub_polaks reply, just trying to help you by giving you a rule to work to.

So I have not included his fix in the above original code with my comments, though this line should be:


// PHP does not expand arrays contained inside double quotes, you have to concat the value back into the string
            print("<option value=\\"$j\\" $selected>" . $hex_array[$j] . "</option>");