Search code examples
phpphp-8

PHP Print "null" instead of nothing



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


Solution

  • 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