Friday, November 06, 2009

Checking for empty variables in PHP

While writing some php code I checked for an empty string, using the empty() function, but I got this error :

PHP Fatal error:  Can't use method return value in write context
I found this very strange because I've used the empty() function many times before. It turns out that the empty() function can not handle the return value of a function or method. You can only check variables using this function.

The solution is simple, store the return value of a function in a variable, and then check the variable with the empty() function :

if ( empty ( some_function() ) ) {

$some_variable = some_function();
if ( empty ( $some_variable ) ) {

On a side note, using the empty() function, is the best way to check for an empty variable, because it combines multiple checks, and works for different variable types. See documentation for details. When relying solely on strlen() or isset(), you can get an unexpected result.

No comments: