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 );
}
So
empty()is more than just the inverse ofisset().It tests for "non-falseness".
One could equate it with:
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
issetcheck. Another common idiom is howeverstrlen()or evenstrlen(trim($var))for testing present input text.