PHP - Get bool to echo false when false

前端 未结 14 1650
予麋鹿
予麋鹿 2020-11-22 14:09

The following code doesn\'t print out anything:

$bool_val = (bool)false;
echo $bool_val;

But the following code prints 1:

相关标签:
14条回答
  • 2020-11-22 14:33

    var_export provides the desired functionality.

    This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.

    var_export(true);    // true
    var_export(false);   // false
    var_export(1);       // 1
    var_export(0);       // 0
    var_export(null);    // NULL
    var_export('true');  // 'true'   <-- note the quotes
    var_export('false'); // 'false'
    

    If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:

    var_export((bool) true);   // true
    var_export((bool) false);  // false
    var_export((bool) 1);      // true
    var_export((bool) 0);      // false
    var_export((bool) '');     // false
    var_export((bool) 'true'); // true
    var_export((bool) null);   // false
    
    // !! CAREFUL WITH CASTING !!
    var_export((bool) 'false'); // true
    var_export((bool) '0');     // false
    
    0 讨论(0)
  • 2020-11-22 14:37
    echo(var_export($var)); 
    

    When $var is boolean variable, true or false will be printed out.

    0 讨论(0)
  • 2020-11-22 14:40

    I like this one to print that out

    var_dump ($var);
    
    0 讨论(0)
  • 2020-11-22 14:41

    No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".

    Edit:

    If you really wanted to, you could use an array:

    $boolarray = Array(false => 'false', true => 'true');
    echo $boolarray[false];
    
    0 讨论(0)
  • 2020-11-22 14:43

    This will print out boolean value as it is, instead of 1/0.

        $bool = false;
    
        echo json_encode($bool);   //false
    
    0 讨论(0)
  • 2020-11-22 14:43

    You can use a ternary operator

    echo false ? 'true' : 'false';
    
    0 讨论(0)
提交回复
热议问题