0
0
PHPprogramming~5 mins

Type juggling in PHP

Choose your learning style9 modes available
Introduction
Type juggling helps PHP automatically change data types so your code can work smoothly without you having to convert types yourself.
When you add a number and a string that contains a number, PHP changes the string to a number automatically.
When you compare values with == and want PHP to ignore type differences.
When you get input from users or forms and PHP needs to handle different types without errors.
When you mix different types in expressions and want PHP to handle conversions for you.
Syntax
PHP
$result = $value1 + $value2; // PHP converts types automatically
PHP changes types behind the scenes depending on the operation.
This automatic conversion is called type juggling.
Examples
PHP converts the string "5" to number 5 and adds 10, so the result is 15.
PHP
$a = "5" + 10;
echo $a;
PHP reads the number at the start of the string "10 apples" as 10 and adds 5, result is 15.
PHP
$b = "10 apples" + 5;
echo $b;
Since the string does not start with a number, PHP treats it as 0 and adds 5, result is 5.
PHP
$c = "apples" + 5;
echo $c;
Using == PHP converts types and sees them as equal (true). Using === it checks type too, so false.
PHP
var_dump("5" == 5);
var_dump("5" === 5);
Sample Program
This program shows how PHP converts strings to numbers when adding, and how == compares values ignoring type, but === checks type too.
PHP
<?php
$a = "7" + 3;
$b = "12 cats" + 8;
$c = "dogs" + 4;

echo "a = $a\n";
echo "b = $b\n";
echo "c = $c\n";

if ("10" == 10) {
    echo "10 == 10 is true\n";
}
if ("10" === 10) {
    echo "10 === 10 is true\n";
} else {
    echo "10 === 10 is false\n";
}
?>
OutputSuccess
Important Notes
Type juggling can be helpful but sometimes causes unexpected results, so be careful.
Use === to check both value and type to avoid confusion.
When in doubt, convert types explicitly using (int), (string), etc.
Summary
PHP automatically changes data types in expressions; this is called type juggling.
It helps mix strings and numbers without errors by converting types behind the scenes.
Use strict comparison (===) to avoid surprises caused by type juggling.