In PHP, settype() changes the type of a variable in place. You give it a variable and the name of the type you want, such as 'integer', 'string' or 'array'.
It does the same conversion as a cast like (int) or (string), but it changes the original variable directly instead of returning a new value. Because the variable is passed by reference, the type of $var is different after the call.
Syntax
Call settype() with the values you need. Start with this line.
PHP
settype($value, 'integer');
Call
What it does
settype($v, 'integer')
Changes $v into an int, so '42abc' becomes 42.
settype($v, 'string')
Changes $v into a string, so 5 becomes '5'.
settype($v, 'array')
Wraps a simple value inside an array with one item.
The valid type names are 'bool' or 'boolean', 'int' or 'integer', 'float' or 'double', 'string', 'array', 'object' and 'null'. Casting such as (int) $v is usually shorter when you do not need to change the variable itself.
Library declarations
PHP
settype(mixed &$var, string $type): bool
Parameters
Parameter
Description
var
Required. The variable to convert. It is passed by reference, so the variable itself is changed.
type
Required. The name of the new type: 'bool', 'boolean', 'int', 'integer', 'float', 'double', 'string', 'array', 'object' or 'null'.
Return Value
Return Value
Description
bool
Returns true when the conversion works. In PHP 8, an invalid type name throws a ValueError instead of returning false.
PHP Examples
Example 1 — Changing to Integer and String
Convert a messy string to an int and an int to a string.
Converting a string to an array wraps it. The text becomes the single item at index 0.
Converting to null removes the value. The variable still exists, but it now holds null.
The string '0' becomes false. PHP treats the string zero as a false value.
Each variable changed type in place. No new variable was needed for any of them.
Frequently Asked Questions
It changes the type of a variable in place. For example, settype($x, 'integer') turns the value in $x into an integer and stores it back in $x.
A cast like (int) $x returns a new converted value and leaves $x alone. settype() converts the variable itself. Both follow the same conversion rules.
It accepts 'bool' or 'boolean', 'int' or 'integer', 'float' or 'double', 'string', 'array', 'object' and 'null'. Any other name throws a ValueError in PHP 8.
PHP does not warn you. A float like 3.9 becomes 3 and the string '12abc' becomes 12. Keep a copy of the original value if you may need it again.
It returns true when the type was changed. In PHP 8 and later, an invalid type name throws a ValueError instead, so you do not need to check for false.