Why check if a $_GET variable is empty twice?

212 views Asked by At

Working with PHP some code and I came across some code that basically checks if the same variable is empty twice:

if ( !empty( $_GET[ 'branch' ] ) ) {
    $branch = $_GET[ 'branch' ];
}
if ( empty( $branch ) ) {
    _output( 'Error: no branch specified!' );
    exit( 1 );
}

Any idea why it's set up this way? What is the advantage over just using else, like this:

if ( !empty( $_GET[ 'branch' ] ) ) {
    $branch = $_GET[ 'branch' ];
} else {
    _output( 'Error: no branch specified!' );
    exit( 1 );
}
3

There are 3 answers

1
mario On BEST ANSWER

So empty() is more than just the inverse of isset().

It tests for "non-falseness".
One could equate it with:

if (!isset($var) || $var == false)

Notably it checks with dynamic type conversion. Which in your example probably makes sense, as things like the empty string, or "0", or even "0 sheep" might not make useful branch names.

So it's often quite apt for form input, and explains the use after the isset check. Another common idiom is however strlen() or even strlen(trim($var)) for testing present input text.

2
Devon Bessemer On

It isn't checking if the same variable is empty. $branch isn't necessarily $_GET['branch'] in this code and the first check is to check if $_GET['branch'] isn't empty.

Throughout the code, there is most likely at least one other condition that $branch gets set. This is most likely the last condition, therefore it is checking finally if $branch was set. There might be better ways to resolve this but without seeing the entire code, I couldn't tell you.


Based on your comment below, this is the same thing and even more simple:

$branch = $_GET[ 'branch' ];
if ( empty( $branch ) ) {
    _output( 'Error: no branch specified!' );
    exit( 1 );
}

Why use an if at all on $_GET['branch'] if $branch can only be $_GET['branch']?

Better yet you can use a ternary operator to just set a default branch and avoid the possibility of an error.

$branch = (empty($_GET['branch'])) ? DEFAULT_BRANCH : $_GET['branch'];
0
baao On

Might exist another way that branch gets set and branch will get set later in the code. The first if checks if $_GET is not empty, btw.

There's no reason to do such checks in that way. Like this it looks a bit like code like this:

for ($x=0;$x<2;$x++)
  {
    if ($x>0)
     {
       $x=0;
     }
  }