-1

I have a while-loop to show all Verkopers (or sellers) in a dropdown, this code works as it should:

<select name="verkoper1" class="form-control">
    <option value="0">Geen verkoper aangeduid</option>
        <?php   
        while($aparteVerkoper = mysqli_fetch_assoc($toonVerkopers))
        {
            echo    
            "<option value='".$aparteVerkoper['PK_Verkoper']."'>" .$aparteVerkoper['VerkoperNaam'] . "</option>";
        }
        ?>
</select>

But now I want to add the function that if $row_pandVerkoper[0] equals 4, this option is automatically selected. I tried doing that, but I keep getting unexpected T_IF errors. here is what i tried:

"<option value='".$aparteVerkoper['PK_Verkoper']."' "if ($row_pandVerkoper[0] == '4') echo" selected";">" .$aparteVerkoper['VerkoperNaam'] . "</option>";

If someone can point out what I'm doing wrong, that would be greatly appreciated!

Kevin Verhoeven
  • 179
  • 3
  • 18
  • "if ($row_pandVerkoper[0] == '4') echo" selected";" Remove " before if and " after ; because condition will not be in double quotes. – Rolen Koh Jul 21 '15 at 17:28
  • where did you get this `$row_pandVerkoper[0]` and here `]."' "if` why `.` inside the quote? – Nikson Kanti Paul Jul 21 '15 at 17:31
  • possible duplicate of [if block inside echo statement?](http://stackoverflow.com/q/3507042) and [PHP Parse/Syntax Errors; and How to solve them?](http://stackoverflow.com/a/18092318) – mario Jul 21 '15 at 18:10

1 Answers1

2

You can't place a condition like that in a string.

Your options are to wrap the output in conditions or utilize ternary operations.

What you could do is this:

"<option value='".$aparteVerkoper['PK_Verkoper']."' ".($row_pandVerkoper[0] == '4' ? " selected" : "").">" .$aparteVerkoper['VerkoperNaam'] . "</option>";

Rob W
  • 9,134
  • 1
  • 30
  • 50
  • Thank you for this answer and explanation of ternary operations. The code gave an error though: syntax error, unexpected ')', expecting ',' or ';' I tried deleting that last ")." the error doesnt show up then, but there's also no data in the dropdown anymore. – Kevin Verhoeven Jul 21 '15 at 17:41
  • Thank you. I still have to work a bit on the query itself, but now at least the errors are gone. From now on I'll try to implement ternary operations where possible. – Kevin Verhoeven Jul 21 '15 at 17:55