PHP Type Juggling & Casting
PHP is a loosely typed language, meaning it automatically converts types when needed. This feature, called "type juggling," makes PHP flexible but can also lead to unexpected behavior. Let's master both automatic and explicit type conversion!
What is Type Juggling?
Type juggling is PHP's automatic conversion of values from one type to another based on context. PHP decides the appropriate type without you explicitly telling it.
Click Run to execute your code
Automatic Type Conversion Rules
String to Number
<?php
$str = "123";
$num = $str + 10; // "123" becomes 123
echo $num; // Output: 133
$mixed = "45 apples";
$result = $mixed + 5; // "45 apples" becomes 45
echo $result; // Output: 50
$invalid = "hello" + 5; // "hello" becomes 0
echo $invalid; // Output: 5
?>
Number to String
<?php
$number = 42;
$text = "The answer is " . $number; // 42 becomes "42"
echo $text; // Output: The answer is 42
?>
Boolean Conversions
<?php
// To boolean - these are FALSE:
$false1 = (bool)0;
$false2 = (bool)0.0;
$false3 = (bool)"";
$false4 = (bool)"0";
$false5 = (bool)[];
$false6 = (bool)null;
// Everything else is TRUE:
$true1 = (bool)1;
$true2 = (bool)-1;
$true3 = (bool)"hello";
$true4 = (bool)[1, 2, 3];
?>
| Value | Boolean Equivalent |
|---|---|
false |
false |
0 |
false |
0.0 |
false |
"" (empty string) |
false |
"0" |
false |
[] (empty array) |
false |
null |
false |
| Everything else | true |
Explicit Type Casting
Sometimes you need to force a specific type conversion. Use type casting:
Click Run to execute your code
Casting Syntax
| Cast | Syntax | Example |
|---|---|---|
| Integer | (int) or (integer) |
$i = (int)9.99; |
| Float | (float) or (double) |
$f = (float)42; |
| String | (string) |
$s = (string)123; |
| Boolean | (bool) or (boolean) |
$b = (bool)1; |
| Array | (array) |
$a = (array)"hi"; |
| Object | (object) |
$o = (object)[]; |
Comparison Operators and Type Juggling
Loose Comparison (==)
Compares values after type juggling:
<?php
var_dump(0 == "0"); // true (string "0" becomes 0)
var_dump(0 == ""); // true (empty string becomes 0)
var_dump(0 == false); // true (false becomes 0)
var_dump("10" == 10); // true (string "10" becomes 10)
?>
Strict Comparison (===)
Compares both value AND type (no juggling):
<?php
var_dump(0 === "0"); // false (different types)
var_dump(0 === 0); // true (same type and value)
var_dump("10" === 10); // false (different types)
var_dump(true === 1); // false (different types)
?>
===
and !==) unless you specifically need type juggling. It prevents
unexpected bugs!
Type Conversion Functions
Alternative to casting - use conversion functions:
<?php
// Integer conversion
$int = intval("123"); // 123
$int2 = intval("45.67"); // 45
// Float conversion
$float = floatval("3.14"); // 3.14
// String conversion
$str = strval(123); // "123"
// Boolean conversion
$bool = boolval(1); // true
?>
Strict Typing (PHP 7+)
PHP 7 introduced strict type declarations to prevent automatic type juggling:
<?php
declare(strict_types=1); // Must be first line
function addNumbers(int $a, int $b): int {
return $a + $b;
}
addNumbers(5, 10); // โ
Works
addNumbers(5.5, 10); // โ TypeError!
addNumbers("5", 10); // โ TypeError!
?>
declare(strict_types=1) must be the
very first statement in the file (after opening PHP tag). It only affects the
file it's declared in.
Common Type Juggling Pitfalls
1. Unexpected string to number conversion
<?php
$input = "10 apples";
$result = $input + 5; // โ Gives 15, not error!
// Better approach
if (is_numeric($input)) {
$result = $input + 5;
} else {
echo "Invalid number";
}
?>
2. Loose comparison surprises
<?php
if ("0" == false) { // โ true! Unexpected
echo "This prints!";
}
// Use strict comparison
if ("0" === false) { // โ
false, as expected
echo "This won't print";
}
?>
3. Array to string conversion
<?php
$arr = [1, 2, 3];
echo $arr; // โ Warning: Array to string conversion
// Correct ways
echo implode(", ", $arr); // โ
"1, 2, 3"
print_r($arr); // โ
Shows array structure
?>
Type Juggling in Conditionals
<?php
// These all evaluate to false
if (0) { /* won't execute */ }
if ("") { /* won't execute */ }
if (null) { /* won't execute */ }
if ([]) { /* won't execute */ }
// These all evaluate to true
if (1) { /* executes */ }
if ("0") { /* WAIT! This is false */ }
if ("hello") { /* executes */ }
if ([1]) { /* executes */ }
?>
Exercise: Type Conversion Practice
Task: Fix the type-related bugs in this code!
<?php
// Buggy code
$userInput = "25";
$age = $userInput;
if ($age == "25") {
echo "Age is 25";
}
$total = "100" + "50";
echo $total;
?>
Show Solution
<?php
// Fixed code with proper type handling
$userInput = "25";
$age = (int)$userInput; // Explicit casting
// Use strict comparison
if ($age === 25) {
echo "Age is 25";
}
// Explicit conversion for clarity
$total = (int)"100" + (int)"50";
echo $total; // 150
// Or validate input
if (is_numeric($userInput)) {
$age = intval($userInput);
echo "Valid age: " . $age;
}
?>
Summary
- Type Juggling: Automatic type conversion by PHP
- Happens: During operations, comparisons, function calls
- Casting:
(int),(float),(string),(bool),(array) - Loose (==): Compares after type juggling
- Strict (===): Compares type AND value
- Falsy Values:
false,0,"","0",[],null - Strict Types:
declare(strict_types=1)prevents juggling - Best Practice: Use strict comparison and explicit casting
What's Next?
Now that you understand type juggling, let's dive deep into Strings - one of the most commonly used data types in PHP. You'll learn about string syntax, interpolation, and manipulation!
Enjoying these tutorials?