I would like to know if casting an integer to a boolean in any of these ways is a good idea.
I'm using PHP 7.4
Negating the integer twice (Which seems not optimal to me)
$x = 123;
$bool = !!($x);
Or when I pass the integer as a param and tell it to receive a boolean.
In this case PHP converts the integer to a boolean automatically
negative numbers => true
0 => false
positive numbers => true
function abc(bool $required = true) {
var_dump($required);
}
abc(-123); // bool(true)
abc(0); // bool(false)
abc(123); // bool(true)
I know this is very old but in case someone else stumbled upon this question like myself:
boolval($value)
returns true
/false
based on the integer $value
provided.
This is usually the best way to cast an Int into a Bool.
This is a belated edit: if you want a function to check it:
function CheckNumber($x) {
if ($x > 0)
{$result = true;}
else {
{$result = false;}
return $result;
}
CheckNumber(1);
CheckNumber(-1);
Since i now understand your issue better: boolval
will also return true
on negative numbers. The function i wrote above wont.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With