Types7 min readExamples run on PHP 8.5.10

settype()

Learn how PHP 8.4 settype() converts a variable to another type by reference, which type names it accepts, what it returns, and where it surprises people.

Signature

settype(mixed &$var, string $type): bool

Purpose

settype() converts an existing variable to a different type and stores the result back in that same variable. Unlike a cast such as (int)$x, which gives you a new value, settype() changes the variable you pass in. It is useful when a variable must change type and the type name is only known at runtime, for example when it comes from a configuration array.

Signature

Parameters

  • $var is taken by reference. You must pass a variable, not a literal or the result of a function call. After the call it holds the converted value.
  • $type is a string naming the target type. The documented values are "boolean" or "bool", "integer" or "int", "float" or "double", "string", "array", "object" and "null". There is no default; both arguments are required.

Return value and failures

The function returns true whenever the type name is valid. Because of that, checking the return value tells you nothing about whether the conversion produced a meaningful result. For instance, converting "abc" to an integer succeeds and gives 0.

Two failures are possible in PHP 8:

  • A ValueError is thrown if $type is not a valid type name. Before PHP 8.0 this produced a warning and a false return value, so older code that tests for false no longer sees that path.
  • A TypeError is thrown if $var is a reference to a typed property and the converted value cannot be assigned to the declared type. When coercive typing is active and the value can be coerced back to the property's type, the property keeps its declared type and the call still returns true.

Example 1: the basic conversion

A numeric prefix is used when a string becomes an integer, and true becomes the string "1".

Example
<?php
$foo = "5bar";
$bar = true;

settype($foo, "integer");
settype($bar, "string");

var_dump($foo, $bar);
Output
int(5)
string(1) "1"

Example 2: arrays, truncation and null

A scalar converted to "array" is wrapped in a one-element array. A float converted to an integer drops its fractional part. Converting to "null" discards the value entirely, yet the call still returns true.

Example
<?php
$a = "text";
settype($a, "array");

$b = 3.99;
settype($b, "int");

$c = "abc";
$ok = settype($c, "null");

echo json_encode([$a, $b, $ok, $c], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
[["text"],3,true,null]

Example 3: an invalid type name

PHP 8 rejects unknown type names with an exception, and the variable is left untouched.

Example
<?php
$value = "10";

try {
    settype($value, "number");
} catch (ValueError $e) {
    echo get_class($e), "\n";
}

var_dump($value);
Output
ValueError
string(2) "10"

Edge cases

  • Converting a string without a numeric prefix to "int" or "float" gives 0 or 0.0. No error is raised, so validate input first if the distinction matters.
  • Converting null to "array" gives an empty array, while converting a scalar gives a one-element array.
  • Converting an array to "int" gives 0 for an empty array and 1 for a non-empty one. This rarely matches what you want.
  • Converting an array to "object" produces a stdClass whose properties are the array keys.
  • "double" is accepted as an alias for "float", and gettype() still reports floats as "double".
  • Integer results are bounded by PHP_INT_MAX, so very large numeric values do not convert the way they look.

Common mistakes

  1. Treating the return value as success. It is true for every valid type name, so it does not validate the data.
  2. Passing a literal or an expression. The first argument needs a variable because it is passed by reference.
  3. Using a wrong type name. Names such as "number" or "integer " throw ValueError. Prefer the documented spellings.
  4. Expecting a typed property to change type. A property declared int stays an int; the value is coerced back or a TypeError is thrown.
  5. Using it where a cast is clearer. If the target type is known when you write the code, (int)$x or intval() is shorter and does not modify the original variable.
  • gettype() reports the current type name of a variable.
  • get_debug_type() returns a type name suited to messages.
  • intval(), floatval(), strval() and boolval() return converted values without modifying the input.
  • var_dump() shows both the type and value, which helps while debugging conversions.

Recap

settype() converts a variable in place using a type name given as a string. It returns true for all valid names, throws ValueError for invalid ones in PHP 8, and may throw TypeError for typed property references. Remember that lossy conversions succeed silently, so validate input first when correctness matters.

Tested examples

Basic conversion of a string and a boolean
<?php
$foo = "5bar";
$bar = true;

settype($foo, "integer");
settype($bar, "string");

var_dump($foo, $bar);
Output
int(5)
string(1) "1"
Arrays, truncation and null
<?php
$a = "text";
settype($a, "array");

$b = 3.99;
settype($b, "int");

$c = "abc";
$ok = settype($c, "null");

echo json_encode([$a, $b, $ok, $c], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
[["text"],3,true,null]
Invalid type name throws ValueError
<?php
$value = "10";

try {
    settype($value, "number");
} catch (ValueError $e) {
    echo get_class($e), "\n";
}

var_dump($value);
Output
ValueError
string(2) "10"