strval
strval($value)
Converts a value to a string. It does the same as the cast (string) $value. As a function it is useful where a function name is needed – for example in array_map().
Parameters
- $value – a number, a boolean, null, a string or an object with the __toString() method.
Examples
var_dump(strval(42)); // string(2) "42"
var_dump(strval(1.50)); // string(3) "1.5"
var_dump(strval(3.0)); // string(1) "3"
// true is "1", false and null an empty string
var_dump(strval(true)); // string(1) "1"
var_dump(strval(false)); // string(0) ""
var_dump(strval(null)); // string(0) ""
// the same as the cast
var_dump(strval(42) === (string) 42); // bool(true)
// converting all array elements
var_dump(array_map("strval", array(1, 2.5)) === array("1", "2.5")); // bool(true)
// very large and very small numbers are converted to exponent notation
echo strval(1e25); // 1.0E+25
echo strval(0.00001); // 1.0E-5
// an object with the __toString method
class ProductPrice {
private $amount = 449;
public function __toString() { return $this->amount . " USD"; }
}
echo strval(new ProductPrice()); // 449 USD
// numbers for readers are formatted by number_format
echo number_format(1234.5, 2, ".", ","); // 1,234.50
Things to watch out for
- false is converted to an empty string, not to "0". Convert a true/false value for printing explicitly, for example to "yes" or "no".
- An array cannot be converted – the result is the text "Array" and an error message (a Notice in PHP 7, a Warning in PHP 8). Arrays are joined by implode(), for debugging there is print_r() or json_encode().
- An object without the __toString() method causes an error (Error).
- In PHP 7 the conversion of a float depends on the locale: after setlocale() with a German or Czech locale strval(1.5) returns the text "1,5" with a comma, which cannot be used in a calculation or in an SQL query. Since PHP 8.0 the conversion always uses a dot.
- By default floats are converted to at most 14 significant digits (the precision directive). An exact number of decimal places is set by number_format() or sprintf().
Related functions:
is_string()
number_format()
sprintf()