settype

Converts a variable in place to a given type, changing the original variable by reference.

Signature
settype(mixed &$var, string $type): bool
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$varmixedThe variable being converted. It is modified in place, so it must be a variable, not a literal or expression.
$typestringThe target type: "bool"/"boolean", "int"/"integer", "float"/"double", "string", "array", "object" or "null".

Return value

booltrue on success or false on failure.

Errors

Throws a ValueError if type is not one of the accepted type names.

Changelog

  • PHP 8.0.0Throws a ValueError when an invalid type name is passed. Previously an E_WARNING was emitted and false was returned.

settype() changes a variable's type in place. Because the parameter is by reference, you pass a variable and it is rewritten — there is no return value to assign, only a bool saying whether the conversion was accepted.

When to reach for it

Honestly, rarely. A cast — $n = (int) $n; — does the same job, is faster, is obvious to readers and static analysers, and works on expressions rather than only on variables. settype() earns its place when the target type is dynamic: coercing a row of values against a schema map, or normalising query-string parameters where the expected type comes from configuration rather than source code.

What trips people up

Conversion is lossy and silent. "42abc" becomes 42, 3.99 becomes 3, and nothing warns you. Validate with is_numeric() first if the input might be junk.

Since PHP 8.0 an unrecognised type name throws a ValueError instead of returning false, so code that checked the return value now needs a try block. "resource" has never been a valid target.

Converting a scalar to "array" wraps it as [$value], and to "object" produces a stdClass with a scalar property — surprising if you expected an empty container. null converts to an empty array, not [null].

Example

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

When to use it

  • Coercing a row of CSV strings against a column-type map read from config
  • Normalising query-string parameters to types declared in a route definition
  • Applying a stored schema to decoded JSON before handing it to typed code

Frequently asked questions

What is the difference between settype and a type cast?

A cast such as (int) $x produces a new value and leaves the original alone, while settype() modifies the variable in place and returns a bool. Prefer the cast unless the target type is determined at runtime.

Why does settype return true instead of my converted value?

Because the variable is passed by reference and rewritten in place; the return value only reports success. Never write $x = settype($x, 'int') — that replaces $x with the boolean true.

What types can settype convert to?

"bool"/"boolean", "int"/"integer", "float"/"double", "string", "array", "object" and "null". Anything else, including "resource", throws a ValueError as of PHP 8.0.

More examples

Applying a schema to raw input

This is the case a cast cannot cover: the target type lives in data, not in the source. settype() writes each element in place, turning the all-string row into properly typed values.

Example · php
<?php
$row    = ['id' => '17', 'price' => '9.99', 'active' => '1', 'name' => 'Pen'];
$schema = ['id' => 'int', 'price' => 'float', 'active' => 'bool', 'name' => 'string'];

foreach ($schema as $field => $type) {
    settype($row[$field], $type);
}

var_dump($row);

settype versus a cast

The cast leaves $x untouched and hands back a new value; settype() rewrites $x and returns only true. The last block shows that converting a scalar to an object yields a stdClass with a single scalar property.

Example · php
<?php
$x = '7.9';

$cast = (int) $x;
echo "cast: ", var_export($cast, true), " | \$x still ", var_export($x, true), "\n";

$ok = settype($x, 'int');
echo "settype returned ", var_export($ok, true), " | \$x now ", var_export($x, true), "\n";

$y = 5;
settype($y, 'object');
var_dump($y);

Discussion

  • Be the first to comment on this lesson.