php 将空值转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9913447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert null to string
提问by laukok
Is it possible to convert null
to string
with php?
是否有可能转换null
到string
用PHP?
For instance,
例如,
$string = null;
to
到
$string = "null";
回答by dev-null-dweller
var_exportcan represent any variable in parseable string.
var_export可以表示可解析字符串中的任何变量。
回答by Matt Ball
Am I missing something here?
我在这里错过了什么吗?
if ($string === null) {
$string = 'null';
}
was thinking something shorter...
在想更短的东西......
You can do it in one line, and omitthe braces:
if ($string === null) $string = 'null';
You can also use the conditional operator:
您还可以使用条件运算符:
$string = ($string === null) ? 'null' : $string;
Your call.
您的来电。
回答by Omar
in PHP 7 you can use Null coalescing operator ??
在 PHP 7 中,您可以使用 Null 合并运算符 ??
$string = $string ?? 'null';
回答by dvvrt
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($string, true)
在其他回复中提到)退货'NULL'
回答by Oleksi
if ($string === null)
{
$string = "null";
}
回答by user1303559
it has best solution:
它有最好的解决方案:
$var = null;
$stringNull = json_encode($var);
$null = json_decode($stringNull, true);
var_dump($stringNull);
var_dump($null);