PHP - Get bool to echo false when false

前端 未结 14 1867
予麋鹿
予麋鹿 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条回答
  •  -上瘾入骨i
    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("

    %s

    %s
    %s

    ", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");

提交回复
热议问题