Signature
settype(mixed &$var, string $type): boolPurpose
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
$varis 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.$typeis 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
ValueErroris thrown if$typeis not a valid type name. Before PHP 8.0 this produced a warning and afalsereturn value, so older code that tests forfalseno longer sees that path. - A
TypeErroris thrown if$varis 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 returnstrue.
Example 1: the basic conversion
A numeric prefix is used when a string becomes an integer, and true becomes the string "1".
$foo = "5bar";
$bar = true;
settype($foo, "integer");
settype($bar, "string");
var_dump($foo, $bar);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.
$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";[["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.
$value = "10";
try {
settype($value, "number");
} catch (ValueError $e) {
echo get_class($e), "\n";
}
var_dump($value);ValueError string(2) "10"
Edge cases
- Converting a string without a numeric prefix to
"int"or"float"gives0or0.0. No error is raised, so validate input first if the distinction matters. - Converting
nullto"array"gives an empty array, while converting a scalar gives a one-element array. - Converting an array to
"int"gives0for an empty array and1for a non-empty one. This rarely matches what you want. - Converting an array to
"object"produces astdClasswhose properties are the array keys. "double"is accepted as an alias for"float", andgettype()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
- Treating the return value as success. It is
truefor every valid type name, so it does not validate the data. - Passing a literal or an expression. The first argument needs a variable because it is passed by reference.
- Using a wrong type name. Names such as
"number"or"integer "throwValueError. Prefer the documented spellings. - Expecting a typed property to change type. A property declared
intstays anint; the value is coerced back or aTypeErroris thrown. - Using it where a cast is clearer. If the target type is known when you write the code,
(int)$xorintval()is shorter and does not modify the original variable.
Related functions
gettype()reports the current type name of a variable.get_debug_type()returns a type name suited to messages.intval(),floatval(),strval()andboolval()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
$foo = "5bar";
$bar = true;
settype($foo, "integer");
settype($bar, "string");
var_dump($foo, $bar);int(5) string(1) "1"
$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";[["text"],3,true,null]
$value = "10";
try {
settype($value, "number");
} catch (ValueError $e) {
echo get_class($e), "\n";
}
var_dump($value);ValueError string(2) "10"