Null and Empty Strings - Making Null Safe in PHP (
Page 2 of 4 )
A safe way to to handle this problem would be to use a custom isNull function, like so:
function isNull($var) {
if(is_null($var)) {
return true ;
} else if((string)$var == "") { // $var == "" will return true if $var = 0 that's why we need to cast into string
return true ;
} else if(count($var) < 1) { // return true even if its an empty array
return true ;
} else {
return false ;
}
}
Now the functional code becomes:
If ( isNull($var) ) { // returns true when var has value and $var is not equal to zero
echo $var ; // or do some processing
}
If your code is all object-oriented, you can put the function in one of the general classes as shown below:
Class GenClass
{
// class vars
....
function isNull()
{
.......
}
} // end of class
The functional code in this case becomes:
If ( $genClass->isNull($var) ) { // returns true when var has value and $var is not equal to zero
echo $var ; // or do some processing
}