phphtmlternary-operator

Ternary Operator makes html closing tags not visible


I'm creating a very basic and simple validation for empty fields using the ternary operator.

Code:

<?php
    echo "<span class='error'>" . $error = (isset($_POST['naam']) && empty($_POST['naam'])) ? 'Required field' : test_input(isset($_POST['naam'])) . "</span>"
?>

Whole line

echo "<div class='form-group'><Label for='name'>Voorstelling naam</Label><input type='text' name='naam' value='".$row['naam']."' placeholder='Naam'><span class='error'>" . $error = (isset($_POST['naam']) AND empty($_POST['naam'])) ? 'Dit is een verplicht veld' : test_input(isset($_POST['naam'])) . "</span></div>";

The code is working fine but the </span>tag is not working/visible in the browser


Solution

  • With your updated code, try just removing the $error = assignment portion. You're also passing the isset return value into test_input which may not be what you want.

    Because of the ternary in the $error = assignment, the "</span></div>" is only being appended to the failure case of the check.

    echo "<div class='form-group'><Label for='name'>Voorstelling naam</Label><input type='text' name='naam' value='".$row['naam']."' placeholder='Naam'><span class='error'>" . 
        $error = (isset($_POST['naam']) AND empty($_POST['naam'])) ? 
            'Dit is een verplicht veld' : // No added "</span></div>" here, doesn't close!
            test_input(isset($_POST['naam'])) . "</span></div>"
    ;