PHP Casting
In PHP, casting is the process of converting a variable from one data type to another. PHP is a loosely typed language, so it often does type juggling automatically, but you can also explicitly cast variables.
Syntax
Common Casts in PHP
Type Cast | Description | Example |
---|---|---|
(int) or (integer) |
Cast to integer | $a = (int) "123"; |
(bool) or (boolean) |
Cast to boolean | $a = (bool) 1; |
(float) or (double) or (real) |
Cast to float | $a = (float) "12.3"; |
(string) |
Cast to string | $a = (string) 123; |
(array) |
Cast to array | $a = (array) "value"; |
(object) |
Cast to object | $a = (object) $array; |
(unset) |
Cast to NULL (rarely used) | $a = (unset) $value; |
Examples
Notes
-
PHP automatically casts types in many situations (e.g., in arithmetic or comparisons).
-
Use explicit casting when you need to be certain about the data type.