0

I'd like to ask if it's possible to print "null" instead of nothingness in php8. Let me explain:
$player = null;
echo $player;

What it prints:
What I want: null

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
Neeko
  • 121
  • 1
  • 8
  • null is a empty string, its like echo ''; – Grumpy Mar 18 '22 at 18:11
  • 2
    I have rolled back your most recent edit. Do not add the solution to the question; post it as an answer below, or accept the answer that was posted properly in the meantime. – Tim Lewis Mar 18 '22 at 18:16
  • 1
    @TimLewis Thank you. I was about to comment an answer but someone already answered again. I will mark it as solved. – Neeko Mar 18 '22 at 18:19

1 Answers1

2

Depending on what "nothingness" means to you, you could use one of the following:

echo $player ?? 'null'; // null coalescing operator

// or

echo $player ? $player : 'null'; // ternary operator

// or

echo !empty($player) ? $player : 'null'; // ternary operator with empty() check, which will not throw an error when the $player variable does not exist 

// or

echo $player ?: 'null'; // ternary operator shorthand

More info here: PHP ternary operator vs null coalescing operator

Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
  • For `null` specific ternary options that can be added as opposed to conditionally falsey values (`0, "", false`), Use `null === $player ? 'null' : $player` and `isset($player) ? $player : 'null'` – Will B. Mar 18 '22 at 18:55