PHP provides several ways to convert between different variable types. Understanding these methods is crucial for working with PHP’s loosely typed nature.
1. Type Casting
The simplest way to convert types is by prefixing the variable with the target type in parentheses.
1 2 3 4 5 6 |
$var = (int) "123"; // Convert to integer (123) $var = (float) "3.14"; // Convert to float (3.14) $var = (string) 123; // Convert to string ("123") $var = (bool) 1; // Convert to boolean (true) $var = (array) "hello"; // Convert to array (["hello"]) $var = (object) ["a"=>1]; // Convert to object (stdClass with property 'a') |
2. Type Conversion Functions
PHP provides functions that return the converted value without changing the original variable.
1 2 3 4 |
$int = intval("456"); // Returns 456 (integer) $float = floatval("7.89"); // Returns 7.89 (float) $str = strval(123); // Returns "123" (string) $bool = boolval(0); // Returns false (boolean) |
These functions are useful when you want to keep the original variable unchanged.
3. settype() Function
This function changes the type of a variable in-place (modifies the original variable).
1 2 3 4 5 |
$var = "123"; settype($var, "integer"); // $var is now 123 (integer) $var = 3.14; settype($var, "string"); // $var is now "3.14" (string) |
4. Automatic Type Juggling
PHP automatically converts types in many contexts:
1 2 |
$sum = "5" + 2; // Result is 7 (integer) $concat = "5" . 2; // Result is "52" (string) |
Key automatic conversion rules:
+
operator converts to numbers.
operator converts to strings- Comparisons have special type conversion rules
5. Special Conversion Functions
For more complex conversions between specific types:
1 2 3 4 5 6 7 8 9 10 11 |
// String to array and vice versa $array = explode(",", "a,b,c"); // ["a", "b", "c"] $string = implode(",", ["a","b","c"]); // "a,b,c" // JSON conversions $json = json_encode(["name" => "John"]); // '{"name":"John"}' $array = json_decode($json, true); // ["name" => "John"] // Serialization $serialized = serialize(["a", "b"]); // 'a:2:{i:0;s:1:"a";i:1;s:1:"b";}' $original = unserialize($serialized); // ["a", "b"] |
6. Boolean Conversion Rules
Values that convert to false
in boolean context:
- The boolean
false
itself - Integer
0
and float0.0
- Empty string
""
and string"0"
- Empty array
[]
NULL
All other values convert to true
.
Best Practices
- Be explicit with type conversions when the context isn’t clear
- Use strict comparisons (
===
) when type matters - Validate input before converting (e.g., with
is_numeric()
) - Document expected types in function signatures