简体   繁体   中英

How to check if multiple values are isset() from a HTML form

I keep trying to find how to do this online and I am unable to find it. I have the following:

if (isset($_GET['the_country']))

I have a selection box in an html form for "the_country" and "the_city". I want to have an if statement for if the_country is set, the_city is set, and if the_country and the_city are set. How would I make the if statements read if I want them to run like this. I see the issue coming where even if both are set, it would take my first if statements also because they are each set on their own. How would I basically convert this into the following:

If(the_country is set and the the_city not set) If(the_city is set and the the_country not set) If(the_country is set and the the_city is set)

With the current input structure, you can divide the conditions into 4 blocks:

$isCountry = isset($_GET['the_country']);
$isCity = isset($_GET['the_city']);

if ($isCountry && $isCity) {
    // both set
} elseif ($isCountry && !$isCity) {
    // only country set
} elseif (!$isCountry && $isCity) {
    // only city set
} else {
    // none set
}

Method 1:

It can be done in many ways. But a more straightforward approach is writing the if-else directly.

if (isset($_GET['the_country']) && if (isset($_GET['the_city'])) {
 // both the country and the city are set
} else if (isset($_GET['the_country']) && !isset($_GET['the_city'])) {
    // country is set city is not set
} else if (!isset($_GET['the_country']) && isset($_GET['the_city'])) {
    // country is not set the city is set
} else {
    // both country and city are not set
}

isset checks if the variable is set. It will return true even if the variable is assigned a null value.

<?php
$a='';
var_dump(isset($a));// true
var_dump(isset($b));// false

If you need to check if the_city and the_country have a valid input, use empty() instead of isset() .

Method 2:

Obviously, it will become more complicated as the number of inputs increases. You will be having a lengthy if-else-if ladder in your code.

To avoid that you can write a validation logic as shown below:

$inputFields = [
    'the_city' => null,
    'the_country' => null,
];

$userInput = array_merge($inputFields, $_GET);

$validated = array_filter($userInput, function($val) {
    return $val !== null;
});

$errors = array_diff_key($userInput, $validated);

if (! empty($errors)) {
    echo 'The fields ' . implode(',', array_keys($errors)) . ' are empty';
}

Also, you can consider writing a validation class with the same logic for code reuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM