Convert null to string
27,134
Solution 1
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.
Solution 2
in PHP 7 you can use Null coalescing operator ??
$string = $string ?? 'null';
Solution 3
var_export can represent any variable in parseable string.
Solution 4
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'
Comments
-
Run almost 2 years
Is it possible to convert
null
tostring
with php?For instance,
$string = null;
to
$string = "null";
-
Run about 12 yearsno u didn't. i just thought there might be a way without using if condition... guess not :-)
-
Matt Ball about 12 yearsWhat's the problem with using
if
? -
user1303559 over 11 yearsi think use case for this is only $str = "ergergegE".($string === null ? "null" : $string)."ergegrregege"; it very long string:) $str= "regregrege".json_encode($string)."ergegergerge"; is shortest and universally
-
Vladislav Rastrusny over 9 yearsSeem to be the slowest and overcomplicated
-
ToolmakerSteve over 4 yearsWon't do what is wanted, if the string is empty
''
, because PHP's==
operator considersnull
to be equal to an empty string. This is why the accepted answer uses===
operator instead. See PHP type comparison tables, scroll down to the table labeled "Loose comparisons with ==".