6.9. Returning Failure
Problem
You want to indicate failure from a function.
Solution
Return false:
function lookup($name) {
if (empty($name)) { return false; }
...
}
if (false !== lookup($name)) { /* act upon lookup */ }Discussion
I
n PHP, non-true values aren’t
standardized and can easily cause errors. As a result,
it’s best if all your functions return the defined
false
keyword because this works best when
checking a logical value.
Other possibilities are ''
or 0. However,
while all three evaluate to non-true inside an if,
there’s actually a difference among them. Also,
sometimes a return value of 0 is a meaningful
result, but you still want to be able to also return failure.
For example, strpos( )
returns the location of the first substring
within a string. If the substring isn’t found,
strpos( ) returns false. If it
is found, it returns an integer with the position. Therefore, to find
a substring position, you might write:
if (strpos($string, $substring)) { /* found it! */ }However, if $substring is found at the exact start
of $string, the value returned is
0. Unfortunately, inside the
if, this evaluates to false, so
the conditional is not executed. Here’s the correct
way to handle the return value of strpos( ):
if (false !== strpos($string, $substring)) { /* found it! */ }Also, false is always guaranteed to be
false — in the current version of PHP and forever more. Other
values may not guarantee this. For example, in PHP 3,
empty('0') was true, but it
changed to false
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access