Rain_xx
Rain_xx

Reputation: 25

PHP into html <option...> code

I'm trying to put this string that work fine as php:

if ($sortvalue == $sort[3]) { echo 'selected=' ;}

into this code:

echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" HERE_THE_PHP_CODE>Price</option>
[..]
</select>';

I tried a lot of syntax but I got always a blank page.

Upvotes: 0

Views: 60

Answers (2)

Marwelln
Marwelln

Reputation: 29433

To keep the code clean you should use the ternary operator. It will allow you to do an if statement inside your echo.

echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" ' . ($sort[3] == $sortvalue ? 'selected' : '') . '>Price</option>
[..]
</select>';

Upvotes: 1

Branndon
Branndon

Reputation: 403

$selected = '';

if ($sortvalue == $sort[3]) { $selected = 'selected'; }

echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" $selected>Price</option>
</select>';

This should do what you want. (the reply by Osama has an error in the if statement)

Upvotes: 2

Related Questions