Vahn Vahn - 1 month ago 7
PHP Question

How can I simplify this PHP script?

I'd like to add "selected" attribute to a combo box. This is my PHP:

if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }

if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }

if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }

if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }


I may have over hundreds of IF's.

I've tried this one, but It seems not working:

for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }

}


I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way

Edit (My combo box):

<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>

Answer

Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!

// initialize all 4 to blank
for($a=1; $a<=4; $a++){
    ${"ok" . $a} = "";
}
// set the one that is selected 
${"ok" . $results['status']} = "selected";

This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.

Comments