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'

Share:
27,134
Run
Author by

Run

A cross-disciplinary full-stack web developer/designer.

Updated on August 02, 2022

Comments

  • Run
    Run almost 2 years

    Is it possible to convert null to string with php?

    For instance,

    $string = null;
    

    to

    $string = "null";
    
  • Run
    Run about 12 years
    no u didn't. i just thought there might be a way without using if condition... guess not :-)
  • Matt Ball
    Matt Ball about 12 years
    What's the problem with using if?
  • user1303559
    user1303559 over 11 years
    i 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
    Vladislav Rastrusny over 9 years
    Seem to be the slowest and overcomplicated
  • ToolmakerSteve
    ToolmakerSteve over 4 years
    Won't do what is wanted, if the string is empty '', because PHP's == operator considers null 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 ==".