In PHP, strval() returns the string value of a variable. It converts integers, floats, booleans and null to text, and it is the function version of the (string) cast.
You will use strval() when you need a real string, for example before you pass a number to a function that expects text, or when you want to pad or compare values as text. It does not change the original variable. It returns a new string.
Syntax
Call strval() with the values you need. Start with this line.
PHP
$text = strval($value);
Call
What it does
strval(123)
Returns the string '123'.
strval(true)
Returns the string '1'.
strval(null)
Returns an empty string.
strval() works the same as (string) $value. It can convert an object only if its class has a __toString() method. Converting an array gives the word Array and a warning, so avoid it.
Library declarations
PHP
strval(mixed $value): string
Parameters
Parameter
Description
value
Required. The value to convert. It can be any scalar type or an object with __toString(). Do not pass an array.
Return Value
Return Value
Description
string
The string version of the value. true becomes '1', while false and null become an empty string.
PHP Examples
Example 1 — Converting Common Values
Convert an integer, a float, true, false and null, and look at the exact string each one gives.
strval(7) gives the text '7'. str_pad() works on strings, so we convert first.
str_pad() adds zeros on the left. The result is 007, which is always 3 characters long.
strlen(strval(12345)) counts digits. The number has 5 digits, so it prints 5.
The dot joins two strings. '3' and '4' become '34', not the sum 7.
Frequently Asked Questions
It converts a value to a string. For example strval(123) returns '123' and strval(true) returns '1'. It is the function form of the (string) cast.
They give the same result. strval() is a function, so it can be passed as a callback, for example array_map('strval', $numbers). The cast is shorter to write.
An empty string. strval(true) returns '1', which surprises many beginners. strval(null) is also an empty string.
No. An array gives the text 'Array' and a warning. Use implode() to join the items, or json_encode() to get a JSON string.
Only if the class has a __toString() method. Without it, PHP throws an Error saying that the object could not be converted to a string.