Convert native null to string "null"
Asked Answered
C

6

10

Is it possible to convert null to string with php?

For instance,

$string = null;

to

$string = "null";
Conjugal answered 28/3, 2012 at 18:22 Comment(0)
T
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.

Talithatalk answered 28/3, 2012 at 18:24 Comment(4)
no u didn't. i just thought there might be a way without using if condition... guess not :-)Conjugal
What's the problem with using if?Talithatalk
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 universallyOzone
@Ozone 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.Lemuellemuela
E
15

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
Eulaeulachon answered 28/6, 2018 at 11:41 Comment(0)
T
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.

Talithatalk answered 28/3, 2012 at 18:24 Comment(4)
no u didn't. i just thought there might be a way without using if condition... guess not :-)Conjugal
What's the problem with using if?Talithatalk
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 universallyOzone
@Ozone 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.Lemuellemuela
S
10

var_export can represent any variable in parseable string.

Sunless answered 28/3, 2012 at 18:28 Comment(2)
This answer is WRONG. In case the value is not null it will be CORRUPTEDLemuellemuela
It's not wrong, it just covers more than null, it is author role to add specific conditions around it.Sunless
C
0
if ($string === null)
{
  $string = "null";
}
Chifforobe answered 28/3, 2012 at 18:24 Comment(0)
M
0

In the narrow context where a variable is ONLY null and the string/word "null" is desired as printed/visible text, there is nothing ugly/unintuitive about using a null coalescing operator, ternary statement, or a comparatively verbose verbose if. Just be sure to encapsulate your logic with parentheses if you are concatenating the value to another string.

Conversely, using a native function call on an unconditionally null value:

  • will be less intuitive for a human who is less acquainted with the technique,
  • less performant, but not noticeably so -- unless you are doing something in the magnitude of millions of times,
  • will have its own unique behavior dictating whether to print NULL or null,
  • in the case of var_dump(), a newline is appended to the printed value.

Here are a battery of solution candidates and their output when fed null as input: (Demo)

$null = null;

echo 'var_export(): ' . var_export($null, true);

echo "\n";

echo 'var_dump(): ' . (function($v){ ob_start(); var_dump($v); return ob_get_clean(); })($null);

//echo "\n";

echo 'print_r(): ' . print_r($null, true);

echo "\n";

echo 'json_encode(): ' . json_encode($null);

echo "\n";

echo 'serialize(): ' . serialize($null);

echo "\n";

echo 'strval(): ' . strval($null);

echo "\n";

echo 'gettype(): ' . gettype($null);

echo "\n";

echo 'null coalesce: ' . ($null ?? 'null');

echo "\n";

echo 'ternary: ' . ($null === null ? 'null' : $null);

echo "\n";

echo 'condition: ' .  (function($v) { if ($v === null) { return 'null'; }})($null);

Output:

var_export(): NULL
var_dump(): NULL
print_r(): 
json_encode(): null
serialize(): N;
strval(): 
gettype(): NULL
null coalesce: null
ternary: null
condition: null

As an extension of the scope of the question, using native functions to convert non-string-type data to printable text:

  • may be ideal if the values have a limited range of possibilities (e.g. nullable boolean values are very well suited to the use of json_encode(),
  • may result in value mutation due to truncation, encoding rules, or even excess characters relating to the value's metadata.

Ultimately, my advice is to use the null coalescing operator (because it is intuitive/self-documenting, concise, and most performant) unless you have a compelling reason to do otherwise.

Mardellmarden answered 26/12, 2023 at 2:34 Comment(0)
O
-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);
Ozone answered 30/3, 2012 at 18:0 Comment(2)
Seem to be the slowest and overcomplicatedMcilwain
It's neither slowest nor overcomplicated. It's just incorrect. Nobody wants their string string to become "string" with quotes.Lemuellemuela

© 2022 - 2024 — McMap. All rights reserved.