PHP Implicit Type Casting
In this article, we will see PHP implicit type casting.
What is PHP Type Casting
Converting one type of data value to another type is called as type casting.
Where: data value can be a literal, variable name, or constant name.
There are 2 types of type casting
Implicit type casting (coercion): done by the PHP engine
Explicit type casting (conversion): done by programmers
Here, we will see only implicit typecasting.
Implicit type casting
If required PHP engine automatically converts one type of data value to another type, which is known as implicit type casting.
Example 1:
We Added integer ‘2’ and float ‘4.3’. So, the integer ‘2’ is converted into float ‘2.0’, then add to ‘4.3’.
echo 2+4.3;
//2.0 + 4.3 = 6.3
Example 2:
Here, add string (25john) and integer (22). The string has an integer at the beginning, so string 25 is converted into integer 25 and then add to 22.
echo "25john" + 22;
//25+22 = 47
Example 3:
In the below code, we add string (john4) and integer (21). The string has integer 4 at the end, so string 4 is converted into integer 0 and then add to 21.
echo "john4" + 21;
//0+21 = 21
Example 4:
In the below code, we multiply the integer (2) and string (4a). The string has integer 4 at the beginning, so string 4 is converted into integer 4. The product of 2 and 4 is 8.
echo 2* "4a";
//2*4=8
Example 5:
Here, we multiply the integer (2) and string (a2). The string has integer 2 at the end, so string 4 is converted into integer 0. The product of 2 and 0 is 0.
echo 2*"a2";
// 2*0=0
Note:
while performing any type of numerical calculations; if a string starts with a valid number then it is extracted out, otherwise the string is converted to 0.