Curriculum
This tutorial will teach you about PHP type juggling and how it works.
PHP is a programming language with a very loose type system. It means you don’t have to declare a type for a variable when you define it. PHP will determine the variable’s type based on the context in which it is used.
If you assign a string to a variable, for example, the variable’s type will be the string:
<?php $my_var = 'PHP'; // a string
And you assign an integer to the same variable, with the integer as its type:
<?php $my_var = 'PHP'; // a string $my_var = 100; // an integer
Type juggling is a feature of PHP. This means that when comparing variables of different types, PHP will convert them to the most common and comparable type. As an example:
<?php $qty = 20; if($qty == '20') { echo 'Equal'; }
PHP converts the string ’20’ to an integer (20) and compares it to the $qty variable due to type juggling. The outcome is correct. As a result, the message Equal will appear in the output.
Type juggling is also useful in arithmetic operations for variables of various types. The example below shows how type juggling works in an arithmetic operation:
<?php $total = 100; $qty = "20"; $total = $total + $qty; echo $total; // 120
$total has an integer type, whereas $qty has a string type. PHP first converts the value of the $qty variable to an integer before calculating the sum. The outcome is an integer.
Consider the following scenario:
<?php $total = 100; $qty = "20 pieces"; $total = $total + $qty; echo $total; // 120
Before calculating the sum, PHP casts the string “20 pieces” as an integer 20.