Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Cast int to boolean

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)

like image 898
Luca Avatar asked Sep 02 '25 15:09

Luca


1 Answers

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.

like image 87
Fuchssprung Avatar answered Sep 05 '25 07:09

Fuchssprung