Predict the output · PHP
PHP 8 String-to-Number Comparison
Medium Predict the output Seen at Automattic, Booking.com, Shopify
What does PHP 8 print?
What does this print?
<?php
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");
bool(true) bool(true) bool(true) bool(true)
bool(false) bool(true) bool(true) bool(true)
bool(false) bool(false) bool(false) bool(true)
bool(true) bool(false) bool(false) bool(false)
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
bool(false) bool(true) bool(true) bool(true)
Since PHP 8.0, comparing a number with a non-numeric string compares them as strings, so 0 == "a" is false (it was true in PHP 7). When both sides are numeric strings, or a number meets a numeric string, PHP still compares numerically: "1" == "01", "10" == "1e1" and 100 == "1e2" are all true.
Use === unless you explicitly want numeric comparison.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium