During PHP development, type conversion is a common operation. As a common tool for converting variables into strings, the strval function has different performances for different types of values. What happens when we use strval to process NULL values? What details do we need to pay special attention to? This article will discuss this issue.
The function of the strval function is to convert the passed parameters into string type, and its function signature is as follows:
strval(mixed $value): string
It receives any type of parameter and returns the string representation of that parameter.
When the parameter is NULL , strval converts it to an empty string.
Examples are as follows:
<?php
$value = NULL;
$result = strval($value);
var_dump($result); // string(0) ""
?>
Output result:
string(0) ""
That is, NULL is converted to an empty string "" .
The internal type conversion rules stipulate:
NULL is converted to a string corresponding to an empty string.
Other types of conversions are performed according to their respective rules.
This is also PHP's tolerant treatment of NULL , which facilitates developers to avoid errors caused by direct output or splicing of NULL values.
Although strval(NULL) will return an empty string, the following points should still be noted in actual use:
Directly use the string concatenator . When connecting NULL , PHP will automatically convert NULL to an empty string.
<?php
$value = NULL;
echo "Value is: " . $value; // Output Value is:
?>
Therefore, the behavior of strval is consistent with the string concatenation operation.
Directly using echo or print to output NULL will also output an empty string and will not throw an error.
<?php
$value = NULL;
echo $value; // 不Output任何内容
?>
The empty string "" obtained using strval(NULL) is the same as the real empty string variable:
<?php
var_dump(strval(NULL) === ""); // bool(true)
?>
However, NULL and empty strings are essentially different types of values, especially in strict type judgments or database operations.
If an array or some object is accidentally passed to strval , a warning or an error will be triggered.
For example:
<?php
$arr = [];
echo strval($arr); // Warning: Array to string conversion
?>
Therefore, it is a good habit to make sure that the parameters passed to strval are not arrays or non-convertible objects.
When using the result of strval(NULL) for URL splicing or HTML output, an empty string may cause missing parameters of the link or incomplete tag attributes. It is recommended to judge or assign a default value in advance.
<?php
// NULLTurn string
$nullValue = NULL;
echo "Using strval: '" . strval($nullValue) . "'\n"; // Output ''
// 直接OutputNULL
echo "Direct echo: '" . $nullValue . "'\n"; // Output ''
// Judge equality
var_dump(strval($nullValue) === ""); // bool(true)
// Warning example
$arrayValue = [];
// echo strval($arrayValue); // Will trigger a warning:Array to string conversion
?>