PHP
⚙️ PHP settype() Function
settype() in PHP is a built-in function used to explicitly convert or modify the data type of an existing variable. Unlike standard type casting which creates a temporary converted copy, settype() directly mutates the original variable's data type.
-
Syntax:
settype(&$var, string $type): bool— Returnstrueon success orfalseon failure. The variable is passed by reference, meaning its value and type are modified permanently in-place.
🛠️ Basic Usage & Code Examples
1️⃣ Converting a String to an Integer
When you pass a numeric string into settype() with the "integer" parameter, the original variable is converted into a true integer type.
$score = "100";
echo gettype($score); // Outputs: string
settype($score, "integer");
echo gettype($score); // Outputs: integer
var_dump($score); // Outputs: int(100)
2️⃣ Converting Numbers to Floating-Point (double)
You can convert an integer or string representation into a float by using "float" or "double".
$price = 45;
settype($price, "float");
echo gettype($price); // Outputs: double
var_dump($price); // Outputs: float(45)
3️⃣ Converting Values to Boolean
Non-empty values resolve to true, while 0, empty strings "", or null resolve to false.
$status = "1";
settype($status, "boolean");
var_dump($status); // Outputs: bool(true)
$emptyVal = 0;
settype($emptyVal, "boolean");
var_dump($emptyVal); // Outputs: bool(false)
4️⃣ Converting Scalar Values to Arrays
Converting a scalar value like a string or number into an array places that value into the first index ([0]).
$siteName = "TeachWebCode";
settype($siteName, "array");
print_r($siteName);
/* Outputs:
Array
(
[0] => TeachWebCode
)
*/
📊 Supported Data Type Strings in settype()
The target type string supplied to settype() must be one of the following valid PHP type aliases:
"boolean"or"bool"→ Casts to boolean."integer"or"int"→ Casts to integer."float"or"double"→ Casts to floating-point number."string"→ Casts to string."array"→ Casts to array structure."object"→ Casts to stdClass object."null"→ Sets variable value to NULL.
-
⚡ settype() vs. Direct Type Casting
-
Direct Casting
(int)$var: Evaluates a converted value on the fly without modifying the original variable. (e.g.,$b = (int)$a;) - settype() Function: Permanently modifies the variable passed to it directly in memory.
