Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading