9

Is it possible to convert null to string with php?

For instance,

$string = null;

to

$string = "null";
hakre
  • 184,866
  • 48
  • 414
  • 792
Run
  • 51,293
  • 159
  • 419
  • 719

6 Answers6

12

in PHP 7 you can use Null coalescing operator ??

$string = $string ?? 'null';
Erenor Paz
  • 2,831
  • 3
  • 37
  • 42
Omar
  • 175
  • 2
  • 5
12

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.

Community
  • 1
  • 1
Matt Ball
  • 344,413
  • 96
  • 627
  • 693
  • no u didn't. i just thought there might be a way without using if condition... guess not :-) – Run Mar 28 '12 at 18:33
  • What's the problem with using `if`? – Matt Ball Mar 28 '12 at 18:34
  • 1
    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 – user1303559 Dec 28 '12 at 22:23
11

var_export can represent any variable in parseable string.

dev-null-dweller
  • 28,932
  • 3
  • 63
  • 85
2

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'

dvvrt
  • 569
  • 6
  • 6
0
if ($string === null)
{
  $string = "null";
}
Oleksi
  • 12,802
  • 4
  • 55
  • 79
  • 1
    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](https://www.php.net/manual/en/types.comparisons.php), scroll down to the table labeled "Loose comparisons with ==". – ToolmakerSteve Aug 22 '19 at 22:01
-1

it has best solution:

$var = null;
$stringNull = json_encode($var);
$null = json_decode($stringNull, true);
var_dump($stringNull);
var_dump($null);
user1303559
  • 440
  • 3
  • 10