Jump to content

is there a shorter better way of doing this?


merylvingien

Recommended Posts

Hi folks, just wondering if there is a quicker, shorter way of coding this:

 

<p>Which of the following best describes your religion:<br>
<select name="religious">
<option <?php if ($religious == 0) {echo 'selected="selected"';} ?> value="0">Non religious</option>
<option <?php if ($religious == 1) {echo 'selected="selected"';} ?> value="1">Christianity</option>
<option <?php if ($religious == 2) {echo 'selected="selected"';} ?> value="2">Hinduism</option>
<option <?php if ($religious == 3) {echo 'selected="selected"';} ?> value="3">Buddhism</option>
<option <?php if ($religious == 4) {echo 'selected="selected"';} ?> value="4">Chinese traditional religion</option>
<option <?php if ($religious == 5) {echo 'selected="selected"';} ?> value="5">Judaism</option>
<option <?php if ($religious == 6) {echo 'selected="selected"';} ?> value="6">Atheist</option>
<option <?php if ($religious == 7) {echo 'selected="selected"';} ?> value="7">Other</option>
</select></p>

 

I have a page with a load of options and to go through all of these is making the code huge. Any quicker ways?

<p>Which of the following best describes your religion:<br>
<select name="religious">
<?php
$arr = array(0 => "Non religious", 1=> "Christianity", 2=> ...);
foreach($arr as $key => $val)
{
  echo '<option ' . ($key == $religious ? 'selected="selected"' : "") . 'value="' . $key . '">' . $val . '</option>'
}
?>
</select></p>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.