2

I need to set the items in a PHP drop down menu based on a number of conditions.

Here's my code:

<select class="span3" id="filter-source">
    <option selected="selected">Select source</option> 
    <?php
    if (($_SESSION['val1']==="value")||($_SESSION['id']==5)) {
        echo '<option';
        if ($val2 == "Something"){
            echo 'selected="selected"';
        }
        echo'Something</option>';
    }
    ?>
</select>

So what I'm doing is displaying the option in the select dropdown only if one the two conditions for the session variables is true. Once 'Something' is selected then $val2 is set as something and on refreshing the page it is displayed as the selected option in the select drop down menu.

This does not result in an server error but the option does not show up at all even if the conditions for the session variables are satisfied.

What am I doing wrong and what is the correct way to do this?

1
  • 2
    Sometimes a quick look at the HTML source is quicker than a post on SO... Commented Oct 18, 2013 at 12:13

2 Answers 2

6

Looks to me like you're not closing your <option> tag, i've added the closing > before 'Something':

<select class="span3" id="filter-source">
            <option selected="selected">Select source</option> 
            <?php
            if(($_SESSION['val1']==="value")||($_SESSION['id']==5))
            {
                echo '<option'; 

                if ($val2 == "Something") {
                    echo 'selected="selected"';
                }

                echo '>Something</option>';
            }
            ?>
</select>

I'd also like to offer up the following piece of cleaner code:

<?php
if(($_SESSION['val1'] === "value") || ($_SESSION['id'] == 5))
{
    echo '<option' . (($val2 == "Something") ? 'selected="selected"' : '') . '>Something</option>';
}
?>
Sign up to request clarification or add additional context in comments.

Comments

2
<select class="span3" id="filter-source" autocomplete="off">
<option selected="selected">Select source</option>
<?php if( $_SESSION['val1']==="value" && $_SESSION['id']==5) { ?>
<option <?php if($_SESSION['val1'] === "value" && $_SESSION['id'] ==5) {echo 'selected="selected"';} ?>> Something</option>
 <?php }?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.