PHP Basic Tutorial
Type casting refers to converting a value from one data type to another.
There are two types of casting in PHP:
Explicit casting is done when you want to manually convert a variable from one type to another using explicit type casts.
0
becomes false
, anything else becomes true
).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
.
Try it yourself
To cast to boolean, use the (bool)
statement:
Try it yourself
When casting to a float, the value is treated as a decimal number.
Try it yourself
You can cast integers, floats, or booleans to strings.
Try it yourself
PHP will not cast arrays to another data type unless you manually handle it with explicit casting.
Try it yourself
Objects converts into associative arrays where the property names becomes the keys and the property values becomes the values.
Try it yourself
To cast to object, use the (object)
statement.
Try it yourself
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.
Try it yourself
To cast to NULL, use the (unset)
statement:
Try it yourself
Implicit casting happens automatically, such as when combining a string with a number.
Try it yourself