The solution: Type safe coding.
<?php
$foo = "1";
$bar = (int)$foo + 1;
var_dump((int)$foo, $bar);
?>
Output
int(1)
int(2)
Use the type safe comparison operators.
<?php
$int = 1;
$string = "1";
$bool = true;
var_dump($int === $string);
var_dump($string === $bool);
var_dump($int === $bool);
?>
Output
bool(false)
bool(false)
bool(false)
The shown mistake is gone:
<?php
function foo($answer) {
if ($answer > 10) {
return true;
} else {
return $answer;
}
}
if (foo(11) === true) {
echo "11 is greater 10<br />";
}
if (foo(9) === true) {
echo "9 is greater than 10<br />";
}
?>
Output
11 is greater 10