After playing with PHP, I discovered that true is returned as 1 and false as null.
echo (5 == 5) // displays 1
echo (5 == 4) // displays nothing
When writing functions that return true or false, what are the best practices for using them?
For example,
function IsValidInput($input) {
if ($input...) {
return true;
}
else {
return false;
}
}
Is this the best way to use the function?
if (IsValidInput($input)) {
...
}
How would you write the opposite function?
IsBadInput($input) {
return ! IsValidInput($input);
}
When would you use the ===
operator?
Sure. Unless you need it in a different sort of structure, e.g. a while loop.
You never would. Always invert the normal function directly.
When you need to differentiate
false
from0
,''
, etc.No..
true
andfalse
are returned as booleantrue
andfalse
. When you echo output it must be cast to a string for display. As per the manual:As for the rest: that's fine, yes, yes, when you want exact type matches, to avoid type juggling in comparisons, e.g.
"1" == true
is true but"1" === true
is false.Your last example is missing an argument, otherwise fine:
That is not true (no pun intended). PHP, like many other languages, has "truthy" and "falsy" values, which can behave like
TRUE
orFALSE
when compared to other values.It is so beause PHP uses weak typing (vs. strong typing). It automatically converts different types of values when comparing them, so it can eventually compare two values of the same type. When you
echo TRUE;
in PHP,echo
will always output a string. But you passed it a boolean value, that has to be converted to a string beforeecho
can do its job. SoTRUE
is automatically converted to the string"1"
, whileFALSE
is converted to""
.This weak, or loose, typing is the reason PHP uses two equality operators,
==
and===
. You use===
when you want to make sure both values you are comparing are not just "equal" (or equivalent), but also of the same type. In practice:Be precise when you can, returning the actual boolean
TRUE
orFALSE
. Typical cases are functions prefixed byis
, likeisValidInput
. One usually expects such functions to return eitherTRUE
orFALSE
.On the other hand, it's useful to have your function return a "falsy" or "truthy" values in some cases. Take
strpos
, for example. If it finds the substring in position zero, it returns0
(int), but if the string is not found, it returnsFALSE
(bool). So: