Convert null to string

laukok picture laukok · Mar 28, 2012 · Viewed 24k times · Source

Is it possible to convert null to string with php?

For instance,

$string = null;

to

$string = "null";

Answer

Matt Ball picture Matt Ball · Mar 28, 2012

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.