I have written a function that returns data on success and false on failure.
I was wondering if this is considered a proper way of evaluating the return value in php.
function data(){
if($all_is_good){
return $data
}else{
return false;
}
}
$data = data(); //basically either a long series of strings or arrays
if(!$data){ //<-- this is the line I'm concerned about, is it safe to assume this?
echo 'oh no, bad stuff happened';
}
Thank you so much!
What you have there is fine, although alternatively, you could use if($data === false) {
. This ensures that $data
is actually false
, considering 0
and NULL
are also seen as false
.
It is safe unless there is a valid value for $data
that would evaluate to false. A long (i.e. nonempty) series of strings or arrays won't evaluate to false, but still it's a potential pitfall.
You might consider using a strict comparison: if(data===False)
It depends in what exactly $data
is (both its type and its value). It makes sense both to leave it as-is (if the type of the value in $data
is not certain) or make the check explicit (e.g. $data == false
or empty($data)
) if it's a known type. It's really dependent on the specific circumstances.