foreach with option select post value

David Noriega asked
php forms

I am doing the verification of a form, I want to choose the selected value if there is an error, the problem is that something is working wrong because when you send the form you add “selected” to all.

foreach ($categorias as $categoria) {
echo "
<option value='".(!empty($_POST["producto_categoria"]) ? $categoria['hijo_id']." selected" : $categoria['hijo_id'])."'>
    {$categoria['padre_nombre']} > {$categoria['hijo_nombre']}

Before sending the form:

enter image description here

After submitting the form:

enter image description here

If the form is sent but there is an error in another part of the form, I want the selected option to be remembered in order to continue with the form.

Any idea where is my error? Thanks in advance!


Your ternary logic is invalid. Here’s a corrected version of your code, which also includes calls to sanitize via htmlspecialchars().

if ( ! empty( $_POST['producto_categoria'] ) ) {
    $producto_categoria = (string) $_POST['producto_categoria'];
foreach ( $categorias as $categoria ) {
    echo '<option' . // Possibly the selected option.
            ' value="' . htmlspecialchars( $categoria['hijo_id'] ) . '"' .
            ( $categoria['hijo_id'] === $producto_categoria ? ' selected' : '' ) . '>' .
            htmlspecialchars( $categoria['padre_nombre'] . ' > ' . $categoria['hijo_nombre'] ) .
Share This
Posted in: