Convert null to string

Am I missing something here?

if ($string === null) {
    $string = 'null';
}

was thinking something shorter...

You can do it in one line, and omit the braces:

if ($string === null) $string = 'null';

You can also use the conditional operator:

$string = ($string === null) ? 'null' : $string;

Your call.


While not very elegant or legible, you can also do the following

is_null($string) && $string = 'null';  // assignment, not a '==' comparison

// $string is 'null'

or

$string = is_null($string) ? gettype($string) : $string;

// $string is 'NULL'

Note: var_export($string, true) (mentioned in other replies) returns 'NULL'


var_export can represent any variable in parseable string.


in PHP 7 you can use Null coalescing operator ??

$string = $string ?? 'null';

Tags:

Php

Null

Isnull