-2

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

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 2
    please take a read on [php falsy value](https://stackoverflow.com/questions/2382490/how-does-true-false-work-in-php) – 0nepeop1e Feb 15 '22 at 06:07
  • 1
    _"how can i make that '0' is not a null value in ternary php"_ - You don't need to do anything. It's the default behavior. Just like `$a ??` and `$b ?? ` won't evaluate as `null`. https://3v4l.org/sHVXk. And if you want to do a type safe comparison, use three `===` instead of two `==`. – M. Eriksson Feb 15 '22 at 06:50
  • oke i understand now thanks – brian christian Feb 15 '22 at 08:15
  • It is only JavaScript which may deliver questionable results is some situations, PHP is rather accurate. – Martin Zeitler Feb 15 '22 at 22:32

1 Answers1

0

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175