PHP - Get bool to echo false when false

前端 未结 14 1671
予麋鹿
予麋鹿 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:44

    json_encode will do it out-of-the-box, but it's not pretty (indented, etc):

    echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));
    

    ...gives...

    {"whatever":true,"somethingelse":false}
    
    0 讨论(0)
  • 2020-11-22 14:45

    Try converting your boolean to an integer?

     echo (int)$bool_val;
    
    0 讨论(0)
  • 2020-11-22 14:50

    The %b option of sprintf() will convert a boolean to an integer:

    echo sprintf("False will print as %b", false); //False will print as 0
    echo sprintf("True will print as %b", true); //True will print as 1
    

    If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.

    Each pattern will be replaced by the argument in order:

    echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");
    
    0 讨论(0)
  • 2020-11-22 14:51

    This gives 0 or 1:

    intval($bool_val);
    

    PHP Manual: intval function

    0 讨论(0)
  • 2020-11-22 14:53
    echo $bool_val ? 'true' : 'false';
    

    Or if you only want output when it's false:

    echo !$bool_val ? 'false' : '';
    
    0 讨论(0)
  • 2020-11-22 14:53

    This is the easiest way to do this:

    $text = var_export($bool_value,true);
    echo $text;
    

    or

    var_export($bool_value)
    

    If the second argument is not true, it will output the result directly.

    0 讨论(0)
提交回复
热议问题