In many programming languages, declaring variables requires variable’s data type and the name of that variable. And then, variables will be initialized, on a need basis, with a value containing same data type as specified in the variable declaration. If any type mismatch occurs, then an exception will be thrown.
But, in PHP, there is no need of any type specification while PHP variable declaration. Rather, it requires only the name of the variable with its value, if any, to be assigned to them.
And, type juggling is one of the features of PHP, provided, to deal with PHP variables. As we have seen already, PHP is a loosely typed language, and hence, capable of taking the data type of the value, as that of the variable, to which that value is assigned.
For example, if we initialize a variable with an integer value, then PHP evaluates the type of the variable as also an integer based on its value. Similarly, if it is a string value, then the same for the variable as well.
Let us look into the following program to know how its behavior according to the PHP type juggling feature.
<?php $number_of_toys = 10; $toys_category = "123 Puzzles"; $toys_age_limit = "5.5"; $toys_price = "2e2"; $result1 = $number_of_toys+$toys_category; $result2 = $number_of_toys+$toys_age_limit; $result3 = $number_of_toys+$toys_price; //output integer value: 133 echo $result1."<br/>"; //output float value: 15.5 echo $result2."<br/>"; //output integer value: 210 echo $result3."<br/>"; ?>
In the first addition expression of the above PHP program results in an integer value, since one of the operands used in this expression is an integer. So, the second operand $toys_category is interpreted as an integer, even though it is a string variable on having a string value.
While interpreting the string as an integer, PHP takes the numeric value with which the string value is started. If the string is not started with numeric values, then, PHP takes 0, while interpreting the string as an integer.
Similarly, it second expression, it results in float value as the output of that addition, since, one of the operands is a float. And then, in third addition, we have added 2e2, returns float value. We can check the type of the results by using PHP variable function gettype().
While dealing with PHP variables data type, if we don’t want this automatic type juggling feature of PHP, there are several ways for casting variable types by explicitly specifying required data type.
If we want to do such explicit type casting for data type conversion, instead of this automatic interpretation, we can use PHP settype() function. Otherwise, we can also use PHP supported type casting syntax by providing required type within parenthesis, for example,
$str_toys_category = (string) $number_of_toys;