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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.