I have very basic question regarding return value of a function, and checking the variable value.
function test($var1, $var2){
if ($var1 == $var2){
$var3 = "abc";
return $var3;
}
return false
}
$value = test($var1, $var2);
if ($value){
echo "Value is".$value; //should output abc.
} else {
echo "Not equal";
}
-
Is it ok to either return a value or return false? For example I am not returning TRUE, it is ok?
-
When i call the function, i store the return value in a variable $value. How can i check the function did return the $var3? Which of the if condition should be used?
if (!empty($value))orif (isset($value))orif ($value)orif (value != false)
Yes, it is common practice in PHP to return
FALSEas an indicator of an error condition. (What constitutes an error is your own decision and depends on what the function is supposed to do.)However, since PHP automatically casts values to Boolean that are of another type (like the empty string or
0, which evaluate toFALSEas well), you should do an explicit check forFALSElike this:As Felix Kling notes in the comments, this is called “strict comparison” (or “identity comparison”). It checks if a value is identical to
FALSE, where as!= FALSE,== FALSEandif ($value)only check if a value could be interpreted asFALSE.