Types7 min readExamples run on PHP 8.5.10

strval()

Learn how PHP 8.4 strval() converts scalars, null and Stringable objects to strings, what it does with arrays and plain objects, and which mistakes to avoid.

Signature

strval(mixed $value): string

Purpose

strval() converts a value to a string and returns the result. It follows PHP's normal rules for converting values to strings, so it behaves like the (string) cast. Because it is a function, you can pass it by name to other functions, for example array_map('strval', $values), which a cast cannot do.

The function does no formatting. It will not pad numbers, fix decimal places or add thousands separators. For that, use sprintf() or number_format().

Signature

Parameters and defaults

$value is the only parameter and it is required, so there are no defaults. The manual says it may be any scalar type, null, or an object that implements __toString(). Scalars are integers, floats, strings and booleans.

Return value

The function always returns a string. The conversions you will meet most often are:

  • Integers become their decimal digits: 42 becomes "42".
  • Floats become their shortest readable text under the current precision setting. 3.5 becomes "3.5", and 2.0 becomes "2" with no trailing .0. Very large or very small floats use exponent notation, such as 1.0E+25.
  • true becomes "1", while false becomes an empty string.
  • null becomes an empty string.
  • A string is returned unchanged.
  • An object with __toString() becomes whatever that method returns.

Failure cases

An object that does not implement __toString() cannot be converted. PHP throws an Error, which you can catch with catch (Error $e).

Arrays are not meant to be passed to strval(). The manual says you cannot use it on arrays. In practice PHP produces the literal text Array and raises a warning about array to string conversion. Treat that result as a bug. If you need to display an array, use json_encode() or implode() instead.

Example 1: scalars and null

This example maps strval over a mixed list. Notice how false and null both vanish into empty strings, and how 2.0 loses its decimal part.

Example
<?php
$values = [42, 3.5, true, false, null, 2.0];
echo json_encode(array_map('strval', $values)), "\n";
Output
["42","3.5","1","","","2"]

Example 2: objects with __toString()

An object can take part in string conversion if its class defines __toString(). The method result is what strval() returns, and it is an ordinary string you can measure or compare.

Example
<?php
class Label
{
    public function __construct(private string $name)
    {
    }

    public function __toString(): string
    {
        return 'Label:' . $this->name;
    }
}

$text = strval(new Label('A'));
echo json_encode([$text, strlen($text)]), "\n";
Output
["Label:A",7]

Example 3: guarding against objects that cannot convert

When the input is not fully under your control, wrap the call so that a plain object does not crash the script. Here a stdClass has no __toString(), so strval() throws an Error.

Example
<?php
function describe(mixed $value): string
{
    try {
        return strval($value);
    } catch (Error $e) {
        return 'not convertible';
    }
}

echo json_encode([describe(12), describe(new stdClass)]), "\n";
Output
["12","not convertible"]

Edge cases

  • Leading zeros are kept in strings. strval("08") is still "08". The string is not turned into a number first, so IDs and postal codes are not harmed.
  • Float output depends on settings. Float text is produced using the precision ini setting. If you need a stable, exact representation for storage or transfer, use json_encode() or an explicit sprintf() format.
  • Negative zero. The float -0.0 converts to "-0".
  • Booleans are not words. strval(false) is an empty string, not "false". If you want readable words, write a conditional.
  • Resources. A resource converts to text such as Resource id #5. That text is only useful for debugging.

Common mistakes

  1. Expecting formatting. strval(1234.5) does not give "1,234.50". Use number_format() for display and sprintf() for fixed decimals.
  2. Passing arrays. The result is the word Array plus a warning, which usually hides a logic error. Convert arrays deliberately with implode() or json_encode().
  3. Treating null as visible text. Empty strings from null and false can make logs and templates look blank. Handle those values before converting if the difference matters.
  4. Assuming every object converts. Only objects with __toString() work. Everything else throws an Error.
  5. Comparing converted values loosely. After conversion both sides are strings, so use === when you want an exact match. "7" and "07" are different strings, even though a loose numeric comparison might treat them as equal.
  • intval() gets the integer value of a variable.
  • floatval() gets the float value of a variable.
  • boolval() gets the boolean value of a variable.
  • settype() changes the type of a variable in place.
  • sprintf() returns a formatted string.
  • number_format() formats a number with grouped thousands.

Recap

strval() returns the string form of a scalar, null or an object with __toString(). It is handy as a callback and equivalent to a (string) cast. It never formats numbers, it returns an empty string for false and null, it throws an Error for objects that cannot convert, and it should not be used on arrays.

Tested examples

Converting scalars and null with array_map
<?php
$values = [42, 3.5, true, false, null, 2.0];
echo json_encode(array_map('strval', $values)), "\n";
Output
["42","3.5","1","","","2"]
Converting an object that implements __toString()
<?php
class Label
{
    public function __construct(private string $name)
    {
    }

    public function __toString(): string
    {
        return 'Label:' . $this->name;
    }
}

$text = strval(new Label('A'));
echo json_encode([$text, strlen($text)]), "\n";
Output
["Label:A",7]
Catching an Error for an object without __toString()
<?php
function describe(mixed $value): string
{
    try {
        return strval($value);
    } catch (Error $e) {
        return 'not convertible';
    }
}

echo json_encode([describe(12), describe(new stdClass)]), "\n";
Output
["12","not convertible"]