0

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.

YKKY
  • 605
  • 1
  • 6
  • 18

1 Answers1

0

$_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';
}
 
KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • Unfortunately your example returns the empty page. There was `empty` and `!empty` before `NULL` and `!NULL`, with the same sad result. – YKKY Aug 22 '21 at 10:20
  • @YKKY That's because of a simple bug. You should [switch on error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display?rq=1), that way PHP will tell you what's wrong. I have corrected the error in the answer. – KIKO Software Aug 22 '21 at 10:21
  • Unfortunately I can't edit php.ini but I've found the missed `}` at the beginning of the 6th string in your example. Looks like I should play with your code any further. May I please also ask what's wrong with my code? – YKKY Aug 22 '21 at 10:27
  • 1
    `empty` after `isset` is redundant. Skip the `isset` and use `empty` as the only test. Or use just `if ($var)` instead of `empty` if you need to distinguish between non-existent and falsey variables. – deceze Aug 22 '21 at 10:31