Advertisement
Google Ad Slot: content-top
PHP Casting
Type casting refers to converting a value from one data type to another.
There are two types of casting in PHP:
Explicit Casting
Explicit casting is done when you want to manually convert a variable from one type to another using explicit type casts.
Supported Data Types for Casting
- (int) or (integer): Converts to an integer.
- (bool) or (boolean): Converts to a boolean (
0becomesfalse, anything else becomestrue). - (float), (double), or (real): Converts to a float.
- (string): Converts to a string.
- (array): Converts to an array.
- (object): Converts to an object.
- (unset): Converts to data type NULL
1) Cast to Integer
When casting a float or string to an integer, the fractional part is removed (truncated), or if the string contains non-numeric characters, it will be converted to 0.
2) Cast to Boolean
To cast to boolean, use the (bool) statement:
3) Cast to Float
When casting to a float, the value is treated as a decimal number.
4) Cast to String
You can cast integers, floats, or booleans to strings.
5) Type Casting in Arrays
PHP will not cast arrays to another data type unless you manually handle it with explicit casting.
Objects converts into associative arrays where the property names becomes the keys and the property values becomes the values.
6) Type Casting in Objects
To cast to object, use the (object) statement.
Indexed arrays converts into objects with the index number as property name and the value as property value.
Associative arrays converts into objects with the keys as property names and values as property values.
7) Cast to NULL
To cast to NULL, use the (unset) statement:
Warning
This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.
Implicit Casting
Implicit casting happens automatically, such as when combining a string with a number.