Is it possible to convert null to string with php?
For instance,
$string = null;
to
$string = "null";
in PHP 7 you can use Null coalescing operator ??
$string = $string ?? 'null';
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'
if ($string === null)
{
$string = "null";
}
it has best solution:
$var = null;
$stringNull = json_encode($var);
$null = json_decode($stringNull, true);
var_dump($stringNull);
var_dump($null);