In PHP, variables are loosely typed, meaning their type can be changed dynamically. Sometimes, you need to convert a variable from one type to another to perform operations correctly. PHP provides the settype() function to explicitly change the type of a variable at runtime.
Using settype() in PHP
The settype() function changes the type of a variable to a specified data type. Its syntax is:
settype(variable, type);
variable– The variable whose type you want to change.type– The target type ("integer","float","string","boolean","array","object").
Examples of Changing Data Types
- Changing to Integer
$value = "100"; settype($value, "integer"); echo $value; // Outputs: 100 echo gettype($value); // Outputs: integer - Changing to Float
$value = "99.99"; settype($value, "float"); echo $value; // Outputs: 99.99 echo gettype($value); // Outputs: double - Changing to String
$value = 123; settype($value, "string"); echo $value; // Outputs: "123" echo gettype($value); // Outputs: string - Changing to Boolean
$value = 0; settype($value, "boolean"); echo $value; // Outputs: (nothing, boolean false) echo gettype($value); // Outputs: boolean - Changing to Array
$value = "Hello"; settype($value, "array"); print_r($value); // Outputs: Array ( [0] => Hello )
Best Practices
- Prefer type casting (
(int),(string)) for simple conversions, but usesettype()when you want to permanently change the variable type. - Always check the type after conversion using
gettype()to avoid unexpected behavior. - Be careful with boolean conversions, as some values may evaluate to
trueorfalsein unexpected ways.
Changing a variable’s type with settype() is a powerful feature in PHP that allows you to handle data flexibly and ensure type compatibility in your applications.
External Reference: PHP Manual
View Other Articles About PHP: Learn PHP Articles