PHP 5 Type Juggling
What is Juggling?
PHP variable types may be modified without any explicit conversion process. This conversion process, whether explicit or implicit, is known as PHP type juggling and is best illustrated with a few examples.
Consider a string and an integer value summed together.
<?php $num1 = "6"; $num2 = "3"; $num3 = 5; $total = $num1 + $num2; // $total holds the value 9. echo "sum=". $total; echo "String + string
"; $total1 = $num1 + $num2 + $num3; echo "
String + string + integer
"; // $total holds the value 14. echo "sum= ".$total1; ?>
In the above example, $num2 and $num2 are string type variable instead of that the value of $total is 9 and $num3 is an integer type variable instead of that it summed with string variable $num1 and $num2.
PHP type juggling example
Let’s take one more example of juggling is the attempt to add an integer and a double. Most certainly the integer would be converted to a double.
<?php $var1 = 8; $var2 = 1.4; $var3 = $var1 + $var2; echo $var3; //$var3 holds 9.4 ?>
In the above example $var1 is an integer and $var2 is a double variable. $var3 convert into the double and store the result.
Integer and string addition example
The addition of an integer and a string containing an integer value as shown below in the example.
<?php $var1=120; $var2 = "150 Laptop for sale"; $var3 = $var1 + $var2; // $var3 holds the value 270. echo $var3; ?>
In the above example, $var1 is an integer variable and $var1 is a string variable that contains some integer value. If you add these two variable result will be 270.