Skip to content
Advertisement

PHP: Can not deal with multiple external conditional variables correctly

It is me who can not deal with multiple external conditional variables correctly, not PHP.

There were several solutions offered by the Stack Overflow while I was preparing this question but none of them seem to suit my case. Sorry if I haven’t made out the correct one.

My goal is to execute one piece of code or just output some text in case the external variable is empty and the other one if not empty.

Say /test.php?test should return something like The variable is empty while /test.php?test=test should return The variable is not empty: test.

I’ve made this code:

if(isset($_GET['test']) and $test === NULL){
    echo 'The variable is empty';
}
if(isset($_GET['test']) and $test !== NULL){
    echo 'The variable is not empty: '.$test;
}

which in my opinion should do the trick. But it doesn’t.

It just returns the if(isset($_GET['test']) and $test === NULL) condition in both cases instead.

I understand that my code is incorrect but I have no idea how to make it working.

Any help will be highly appreciated.

Advertisement

Answer

$_GET always returns a string when an array key exists, it could be an empty string, but a string nonetheless. See: empty()

So your code would look something like this:

if (isset($_GET['test'])) {
    if (empty($_GET['test'])) {
        echo 'The variable is empty';
    } else {
        echo 'The variable is not empty: '.$_GET['test'];
    }
} else {
    echo 'The variable does not exist';
}
 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement