After playing with PHP, I found that true returns as 1 and false as null.
This is incorrect (pun intended). PHP, like many other languages, has “true” and “false” values that can behave like TRUE or FALSE compared to other values.
This is because PHP uses weak typing (compared to strong typing ). It automatically converts different types of values when comparing them, so it can ultimately compare two values of the same type. When you echo TRUE; in PHP, echo always prints a string. But you passed it a boolean that should be converted to a string before echo can do its job. Therefore, TRUE automatically converted to string "1" , and FALSE converted to "" .
When do you use the === operator?
This weak or loose input type is the reason why PHP uses two equality operators == and === . You use === when you want to make sure that the two values you are comparing are not just “equal” (or equivalent), but also of the same type. On practice:
echo 1 == TRUE;
When writing functions that return true or false, what are the best methods for using them?
Be precise when you can, returning the actual logical TRUE or FALSE . Typical cases are functions prefixed with is , for example, isValidInput . Typically, such functions usually return either TRUE or FALSE .
On the other hand, it is useful for your function to return "fake" or "true" values in some cases. For example, strpos . If it finds the substring in the zero position, it returns 0 (int), but if the string is not found, it returns FALSE (bool). So:
$text = "The book is on the table"; echo (strpos($text, "The") == FALSE) ? "Not found" : "Found"; // echoes "Not found" echo (strpos($text, "The") === FALSE) ? "Not found" : "Found"; // echoes "Found"