store false boolean in array

11,571

Solution 1

You may use 1 or 0 for true or false instead. Else, below is another way to do that:

if($a['bool'] === '1') {
    $a['bool'] = intval(true);
} else {
    $a['bool'] = intval(false);
}

Solution 2

use integer 0 or 1 for false or true. It will work like boolean. You should to not use === operator if you use integer as boolean.
you can simple test like this:

if($intVar) {
     //do something it is true
}
else{
 //do something it is false
}

simply asign 0 or 1 in your array like this:

 $a = Array('bool' => 0);

then use it like this:

$sth->execute( $a );

It is not tested but should be work :)

Demo: https://eval.in/98660

 //test for false
  $a = Array('bool' => 0);


    if($a['bool']){
      echo "It is true";
    }
    else {
     echo "It is false \n";
    }

    print_r($a);

    //second test for true

    $a = Array('bool' => 1);




  if($a['bool']){
    echo "It is true";
  }
   else {
     echo "It is false \n";
  }
   print_r($a);

OUTPUT:

It is false 
Array
(
    [bool] => 0
)
It is trueArray
(
    [bool] => 1
)

Solution 3

It does store the boolean value. So when you get the value you should expect a boolean value. If you use var_dump($a) instead of print_r you will see that it is stored perfectly as

array(1) {
  'bool' =>
  bool(false)
}
Share:
11,571
Fez Vrasta
Author by

Fez Vrasta

Updated on June 04, 2022

Comments

  • Fez Vrasta
    Fez Vrasta almost 2 years

    I'm trying to store a false boolean into an array, to pass it as value in a PDO prepared statement:

    $a = Array('bool' => '0');
    
    if($a['bool'] === '1') {
        $a['bool'] = true;
    }
    else {
        $a['bool'] = false;
    }
    
    print_r($a);
    

    The result is:

    Array
    (
        [bool] => 
    )
    

    I would expect:

    Array
    (
        [bool] => 0
    )
    

    Because if I store a true boolean value, the print_r function prints true as value of 'bool'.

    Having the $['bool'] empty doesn't send to my bit field the false value and invalidates my query.

    The value is passed with:

    $sth->execute( $a );
    

    How can I solve the problem?


    For who says "use 1 and 0", well, PDO doesn't accept as boolean values the integers 1 and 0, it needs real booleans.

    • Awlad Liton
      Awlad Liton over 10 years
      use integer 0 or 1 for false or true. It will work like boolean
  • Fez Vrasta
    Fez Vrasta over 10 years
    yes but if I store a true value it is printed out using print_r, instead if is false is not printed.