9

Is it possible to convert null to string with php?

For instance,

$string = null;

to

$string = "null";
Valerio Bozz
  • 1,176
  • 16
  • 32
Run
  • 54,938
  • 169
  • 450
  • 748

5 Answers5

14

in PHP 7 you can use Null coalescing operator ??

$string = $string ?? 'null';

starting from 7.4 you can use Null coalescing assignment operator ??=

$string ??= 'null';

Note that it will suppress the error message if $string doesn't exist. Therefore, it's better to explicitly test the variable with is_null():

$string = null;
$string = is_null($string) ? 'null' : $string;    
var_dump($string); // string(4) "null"

$string = 'string';
$string = is_null($string) ? 'null' : $string;    
var_dump($string); // string(6) "string"

$string = null;
$string = is_null($s) ? 'null' : $string;    
var_dump($string); // Warning: Undefined variable $s
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Omar
  • 203
  • 3
  • 5
12

Am I missing something here?

if ($string === null) {
    $string = 'null';
}

was thinking something shorter...

You can also use a ternary operator:

$string = is_null($string) ? 'null' : $string;

Your call.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    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
  • @user1303559 Universally? What if $string is anything but null? but a string `STRING` for example? `regregrege"STRING"ergegergerge` IS NOT what one would expect from this expression. – Your Common Sense May 05 '23 at 09:03
10

var_export can represent any variable in parseable string.

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
0
if ($string === null)
{
  $string = "null";
}
Oleksi
  • 12,947
  • 4
  • 56
  • 80
-3

it has best solution:

$var = null;
$stringNull = json_encode($var);

you can test it as

$var = null;
$stringNull = json_encode($var);
$null = json_decode($stringNull, true);
var_dump($stringNull);
var_dump($null);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
user1303559
  • 436
  • 3
  • 10