# Simple IF statement, am I doing it right? [closed]

Although I have been coding in PHP for a while now I am trying to go back to basics with some things to make sure by understanding and methods are the most efficient.

I have the following snippet...

if (!empty($_GET['location'])) {$location = $_GET['location']; } else {$location = '';
}


Hopefully the purpose of the snippet should be clear but what I want to know is am I doing it right, is this the most effective way of expressing this simple function?

• The code's purpose, however brief it may be, should still be in the title only.
– Jamal
Apr 1 '15 at 12:59

You can use the ternary operator for this kind of operation, like this:

$location = (empty($_GET['location']) ? '' : $_GET['location'];  It is far more readable. Personaly I prefer this short code: <?php$location=@\$_GET['location'];


I know that purists don't like it, but I totally disagree.
Most notably regarding the "@", which they often say to be avoided since it hides potential errors: yes, generally speaking, but here the "error" is only what we expect when we use empty() and cannot be anything else, so it is totally safe.

NOTE: this is suitable to replace your initial formulation because you wrote if(!empty()), but you should not infer it would be good as well if you write if(!isset()):

• In the first case you simply want to get an empty result whenever no value has been given (and with the short code we get NULL, which in PHP is pretty equivalent to "").
• At the opposite in the latter case, you'll probably want to distinguish between an empty value and no value at all (when the location query param doesn't appear in the URL): then you should keep the if() {...} else {...} formulation.