Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Please explain what happens when PHP switch case executes case 0?
In PHP, when a switch statement compares a string value against case 0, PHP's loose type comparison causes unexpected behavior. The string is automatically converted to an integer for comparison, and any non-numeric string converts to 0.
Type Conversion in Switch Statements
PHP uses loose comparison (==) in switch statements, not strict comparison (===). When comparing a string like "match" with integer 0, PHP converts the string to an integer first.
Example
Here's how the type conversion affects switch case execution −
<?php
switch ("match") {
case 0:
echo "0 with match";
break;
case "match":
echo "match successful";
break;
}
?>
0 with match
Why This Happens
The string "match" converts to integer 0 because it contains no leading numeric characters. PHP's conversion rules −
<?php // Demonstrating string to integer conversion var_dump((int) "match"); // 0 var_dump((int) "123abc"); // 123 var_dump((int) "abc123"); // 0 ?>
int(0) int(123) int(0)
Solution: Use Strict Comparison
To avoid this behavior, place string cases before integer cases or use strict comparison logic −
<?php
// Correct order - string case first
switch ("match") {
case "match":
echo "match successful";
break;
case 0:
echo "0 with match";
break;
}
?>
match successful
Conclusion
PHP's loose type comparison in switch statements can cause unexpected results when mixing string and integer cases. Always place specific string cases before generic numeric cases to ensure proper matching behavior.
