user426404
user426404

Reputation: 58

Get True/False text result from drop down selection

I'm trying to build a drop down menu with a list of city names. For city names where the return value is "true," I want text on the same page to be displayed saying the value is true. If the selection is where the return value is false, I want it to display this as well. I'm working with form actions and php trying to function it and have completely lost it. It's a simple task that I can not for the life of me figure out.

<select name="City">
<option value="Richmond">Richmond</option> //True//
<option value="Bowling Green">Bowling Green</option>//True
<option value="Manakin">Manakin</option>//false//
<option value="Emporia">Emporia</option>//false//
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['City'];  // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; "and this location is Not served" 
// Displaying Selected Value
}
?>

</body>
</html>

Upvotes: 1

Views: 1274

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

I would use an array which holds the state of the values, then you simply check the value which will determine the state.

<?php
$citys = [
    'Richmond' => true, 
    'Bowling Green' => true, 
    'Manakin' => false, 
    'Emporia' => false
];
?>

<select name="City">
<?php foreach ($citys as $city => $avail): ?>
    <option value="<?= $city ?>"><?= $city ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>

<?php
if (isset($_POST['submit'])) {
    $selected_val = $_POST['City'] ?? '';  // Storing Selected Value In Variable

    if (isset($citys[$selected_val])) {
        echo "You have selected:".$selected_val." and this location is ".($citys[$selected_val] ? '' : 'Not').' served';
    } else {
        // error, city not in array
    }
}
?>

Upvotes: 4

Related Questions