Developer Jay
Developer Jay

Reputation: 1373

selected attribute between <option tags in a foreach loop

I'm looking for some guidance here where I've struggled to get working. I have an associative array with the following options:

$options_format [] = [
    'name' => 'Audio',
    'type' => 'Audio',
];

$options_format [] = [
    'name' => 'EBook',
    'type' => 'EBook',
];

$options_format [] = [
    'name' => 'Hardcover',
    'type' => 'Hardcover',
];

$options_format [] = [
    'name' => 'Paperback',
    'type' => 'Paperback',
];

The following for each loop then walks through the array to output the html:

<?php 
    $select = 'selected';
    foreach ($options_format as $key => $value) {
        echo '<option value="' . $value['name'] . '"' . (isset($format) && $format == $value['name']) {  "$select"  };
        echo ">" . $value['name'];
        echo '</option>' . "\n";
    }
?>

The $format variable hold the value for which ever is selected and it will then check if the $format variable is set. But what I'm trying to do is if the form entry has a validation error, it will retain the value of what the user had selected previously.

Any thoughts?

Upvotes: 1

Views: 1178

Answers (2)

Arsalan Akhtar
Arsalan Akhtar

Reputation: 389

Try this you can change $format with your required value.

<?php

$options_format [] = [
    'name' => 'Audio',
    'type' => 'Audio',
];

$options_format [] = [
    'name' => 'EBook',
    'type' => 'EBook',
];

$options_format [] = [
    'name' => 'Hardcover',
    'type' => 'Hardcover',
];

$options_format [] = [
    'name' => 'Paperback',
    'type' => 'Paperback',
];
$format = "Hardcover";
 $select = 'selected';
echo "<select>";

    foreach ($options_format as $key => $value) {
        echo "<option value='".$value['name'] ."' ";
        if($value['name']==$format) 
           echo $select. ">";

        else
            echo ">";

       echo $value['name'] .'</option>' . "\n";
    }
echo "</select>";

?>

Upvotes: 0

R T
R T

Reputation: 1087

$select = 'selected';
foreach ($options_format as $key => $value) {
    echo '<option value="' . $value['name'] . '"' . ((isset($format) && $format == $value['name']) ? "$select" : "")  ;
    echo ">" . $value['name'];
    echo '</option>' . "\n";
}

The way you write your ternary operator:

((isset($format) && $format == $value['name']) ? "$select" : "")

Assuming that $format holds the value of your $_POST['select_field_name'].

Upvotes: 2

Related Questions