strval

Converts any scalar value, null, or object with __toString() into a string.

Signature
strval(mixed $value): string
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$valuemixedThe value being converted to a string. May be any scalar, null, or an object implementing __toString(). Arrays and objects without __toString() cannot be converted meaningfully.

Return value

stringThe string value of $value.

Errors

Throws Error if $value is an object with no __toString() method. Passing an array raises an "Array to string conversion" warning and returns the literal string "Array".

Changelog

  • PHP 8.0Converting an array raises an "Array to string conversion" warning; in PHP 7 this was only a notice.
  • PHP 8.0Converting an object without __toString() throws Error; in PHP 5 and 7 it was a recoverable fatal error.

strval() performs the same conversion as writing (string) $value. It exists mainly so you have a callable version: you can pass strval(...) to array_map(), usort() comparators, or anywhere a callback is expected, which a cast cannot do.

What the conversions look like

InputResult
42"42"
3.0"3"
true / false"1" / ""
null""
object with __toString()whatever that method returns

When to reach for it

Use it when JSON or an API contract demands string IDs and your data holds integers, or when normalising mixed input before a strict comparison. In ordinary inline code prefer the cast — it is clearer and marginally faster.

What trips people up

Floats go through PHP's precision ini setting, not a full-fidelity dump. Large or very precise floats come back in scientific notation (1.0E+25) or rounded to 14 significant digits. For money, database IDs, or anything you will compare as text, use sprintf('%.2f', $n) or number_format() so you control the format instead of inheriting it from an ini setting.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Cast a list of integer database IDs to strings before json_encode() so a JavaScript client does not lose precision on large IDs.
  • Pass strval(...) as the callback to array_map() to normalise a mixed array of ints, floats and booleans into strings.
  • Render a value object (money, version number, UUID wrapper) through its __toString() inside a template.

Frequently asked questions

What is the difference between strval and (string) casting?

Nothing, in terms of result — strval($x) and (string) $x produce identical output. The only reason to use strval() is that it is a callable, so it can be passed to array_map() or any other function expecting a callback.

Why does strval() return an empty string for null and false?

That is PHP's defined string conversion: null and false both convert to "", while true converts to "1". If you need "false" or "null" as visible text, use var_export($value, true) or json_encode() instead.

Does strval() work on arrays?

Not usefully. It returns the literal string "Array" and raises an "Array to string conversion" warning. Use implode(), json_encode() or print_r($array, true) to turn an array into text.

More examples

Use it as a callback with array_map()

var_dump() shows three string(3) entries instead of ints. The two json_encode() lines show the practical payoff: [101,202,303] versus ["101","202","303"], which is what an API expecting string identifiers needs.

Example · php
<?php
$ids = [101, 202, 303];

$asStrings = array_map(strval(...), $ids);
var_dump($asStrings);

echo json_encode($ids), "\n";
echo json_encode($asStrings), "\n";

Float precision: where strval() is the wrong tool

strval() hands large floats back in scientific notation and truncates long decimals at the precision setting. sprintf() and number_format() produce the exact digits you asked for, which is what you want for currency, invoice totals or anything compared as text.

Example · php
<?php
$big = 1.0e25;
echo strval($big), "\n";           // 1.0E+25
echo sprintf('%.0f', $big), "\n";  // full digits

$price = 12.3456789;
echo strval($price), "\n";              // 12.3456789
echo sprintf('%.2f', $price), "\n";     // 12.35
echo number_format($price, 2), "\n";    // 12.35

Objects and arrays behave very differently

An object without __toString() throws an Error naming the class, so you find out immediately. An array does not throw: it quietly becomes the string "Array" after a warning, which is why a stray array in a string context often reaches production unnoticed.

Example · php
<?php
class Tag {
    public function __construct(public string $name) {}
}

try {
    echo strval(new Tag('php'));
} catch (Error $e) {
    echo 'Error: ', $e->getMessage(), "\n";
}

$result = @strval([1, 2, 3]);
var_dump($result);

Discussion

  • Be the first to comment on this lesson.