Convert boolean to integer value php

Solution 1:

http://www.php.net/manual/en/language.types.integer.php

$myInt = (int)$myBoolean should work

Solution 2:

Just add a "+" before your variable like this :

$myBool = true; 

var_dump(+$myBool);

ouputs: int(1);

Solution 3:

// cast to Integer
echo (int)true;         // 1
echo (int)false;        // 0

// get the integer value from argument
echo intval(true);      // 1
echo intval(false);     // 0

// simply echoing true returns 1
echo true;              // 1

// you can even add those values
echo true + true;       // 2

Solution 4:

If you are unsure of the data type see the example below, it works on strings, integers and booleans.

<?php

$options = [ TRUE, FALSE, 'true', 'false', 1, 0, '1', '0', 'on', 'off', 'yes', 'no' ];

foreach ( $options as $option ) {
    $bool = filter_var( $option, FILTER_VALIDATE_BOOLEAN ); // TRUE or FALSE
    print (int) $bool . ' '; // 1 or 0
} 
// Outputs: 1 0 1 0 1 0 1 0 1 0 1 0 

?>

filter_var( $var, FILTER_VALIDATE_BOOLEAN ) will return bool(true) or bool(false) then simply cast as integer.

filter_var()

(PHP 5 >= 5.2.0, PHP 7)

filter_var — Filters a variable with a specified filter