-1
\$\begingroup\$

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?

\$\endgroup\$

closed as off-topic by Jamal Mar 19 '16 at 2:19

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

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

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

$location = (empty($_GET['location']) ? '' : $_GET['location'];

It is far more readable.

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.