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
Number comparisons in PHP 8
PHP 8 introduced significant changes to number comparisons, making them more consistent and predictable. When comparing values, PHP 8 uses number comparison for numeric types, but converts numbers to strings for string comparisons, following stricter rules.
String Categories
Strings can be categorized in three ways −
Numeric string − Contains only numeric characters. Example − "1234" or "1.24e1".
Leading-numeric string − Starts with numeric characters followed by non-numeric characters. Example − "12xyz" or "123 "
Non-numeric string − Cannot be interpreted as numeric. Example − "foo" or "abc123"
PHP 7 vs PHP 8 Comparison Behavior
The most notable change is how PHP handles comparisons between numbers and non-numeric strings −
PHP 7 Behavior
0 == 'foo' // Returns true (converts string to 0)
PHP 8 Behavior
0 == 'foo' // Returns false (saner comparison)
Example
Here's a demonstration of how PHP 8 handles different string types in array keys −
<?php
$x = [
"1" => "first Integer",
"0123" => "The integer index with leading 0",
"12str" => "using leading numeric string",
" 1" => "using leading whitespace",
"2.2" => "using floating number",
];
print_r($x);
?>
Array
(
[1] => first Integer
[0123] => The integer index with leading 0
[12str] => using leading numeric string
[ 1] => using leading whitespace
[2.2] => using floating number
)
Key Changes
| Comparison Type | PHP 7 | PHP 8 |
|---|---|---|
| 0 == "foo" | true | false |
| 0 == "0" | true | true |
| 42 == " 42" | true | true |
Conclusion
PHP 8's saner string-to-number comparisons eliminate unexpected behavior where non-numeric strings were converted to 0. This makes code more predictable and reduces bugs caused by implicit type conversions.
