logo

:: Type Juggling vs Implicit Type Casting in PHP ::

Question:

In PHP, what is the difference between 'type juggling' and 'implicit type casting'?


Answer:

Type juggling occurs when you are assigning a variable a value of a different data type.
Implicit type casting occurs when you are using a variable in a context different to its current data type.

Example:

$a = "10";
$b = 5;
$c = "total";

$c = $a + $b;

In the last line, we are type juggling $c from 'string' to 'int', because we are assigning it an integer value. Also, we are implicitly casting the value of $a from a 'string' to an 'int' because we are using it in a mathematical context.

Note that in the above example we are not type juggling $a. We are simply casting its value and not changing its data type. So you append the below code to the code above, it will still print "string".
echo gettype($a);

<< Back to Questions and Answers

© Copyright php-etc.com 2010. Please contact the webmaster for all enquiries.