merylvingien Posted January 24, 2012 Share Posted January 24, 2012 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 https://forums.phpfreaks.com/topic/255702-is-there-a-shorter-better-way-of-doing-this/ Share on other sites More sharing options...
dzelenika Posted January 24, 2012 Share Posted January 24, 2012 <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 https://forums.phpfreaks.com/topic/255702-is-there-a-shorter-better-way-of-doing-this/#findComment-1310804 Share on other sites More sharing options...
merylvingien Posted January 24, 2012 Author Share Posted January 24, 2012 Thanks for the reply, that echos out the select list fine, but just sticks selected="selected" to 0 regardless of what the actual value of $religious is. Must be close though. Link to comment https://forums.phpfreaks.com/topic/255702-is-there-a-shorter-better-way-of-doing-this/#findComment-1310819 Share on other sites More sharing options...
merylvingien Posted January 24, 2012 Author Share Posted January 24, 2012 Sorry my mistake, it works just fine, thank you very much. Link to comment https://forums.phpfreaks.com/topic/255702-is-there-a-shorter-better-way-of-doing-this/#findComment-1310825 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.