Search code examples
phpternary

How to use ternary operator in php?


When I use ternary operator in PHP I realize that

0, '0',and null is null

so this is little strange, in my opinion that this value '0' considered as a string and no longer considered as null, but the result in ternary this will return to null value

maybe this will be help you

$a=0
$b='0'
$c=null

$a??'it is null'
//it is null
$b??'it is null'
//it is null
$c??'it is null'
//it is null

$a==null?'it is null':'not null'
//it is null
$b==null?'it is null':'not null'
//it is null
$c==null?'it is null':'not null'
//it is null

so what I want to ask is, how can I make that '0' is not a null value in ternary PHP


Solution

  • This is deeper than the ternary operator.

    Boolean logic

    Boolean logic recognizes true and false values, defines relations and operations with these, builds the Boolean algebra upon logical values and their operations.

    PHP (and other languages) supports boolean values of true and false

    Truey and falsy

    If

    $a === true
    

    then $a is true.

    If

    $a == true
    

    then $a is truey. For example, 1 is not true, but it is still truey.

    If

    $b === false
    

    then $b is false. If

    $b == false
    

    then $b is falsy. For example, 0 is falsy, but it is not false.

    You wonder about '0' not being false/falsy. However, logically, the most false string value is '', which is empty string. '0' is longer than ''. 'false' is also a string and different from false.

    Ternary operator

    $a ? $b : $c
    

    evaluates whether $a is truey. If so, then the expression's result is $b. Otherwise the expression's result is $c.