1

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)

Luca
  • 11
  • 2
  • 5
  • 2
    `var_dump((bool) 42);` – u_mulder Jan 21 '21 at 08:50
  • 1
    `(bool) $var` and `!!$var` both accomplish the same. The first is very readable, while the second is an unnecessary hack (and by some reports minutely slower). Don't build for type coercion via method arguments, it will be painful when you switch to strict types. ... Also see [Double not (!!) operator in PHP](https://stackoverflow.com/questions/2127260/double-not-operator-in-php). – Markus AO Jan 21 '21 at 11:02

0 Answers0