Chapter 12
Which PHP Quirks Still Matter?
Test comparison rules, false-or-integer results and array keys against the PHP runtime you use today.

Overview
Section titled “Overview”Some historical criticism of PHP describes behaviour you can still reproduce. Some describes APIs and defaults that have changed. PHP 8 changed how loose comparisons handle numbers and non-numeric strings. The old examples are a good reason to check your runtime and read the exact return type of an unfamiliar function. Eevee’s 2012 critique · PHP 8.0 migration guide
Quick Start
Section titled “Quick Start”Run the script from the repository root with PHP 8.6 or later.
php code/php-misconceptions/quirks.php0 == "php": false0 == "0": true0 === "0": falseMatch at offset 0{"0":"Ada","2":"Linus"}["Ada","Linus"]- Comparison. PHP 8 no longer treats a non-numeric string like
"php"as zero when loosely comparing it to a number. The numeric string"0"still compares equal to0with==. Use===when the type is part of the comparison. The example already usesstrict_types=1, which does not change the behaviour of==. Number and string comparisons - Return values.
strpos()returns a zero-based byte offset orfalse. A truthiness check treats offset zero as false. Use!== falseto check whether you got a position, orstr_contains()for a Boolean answer. strpos · str_contains - Arrays. PHP arrays are ordered maps. Unsetting the middle element here leaves keys 0 and 2, so JSON encodes the remaining map as an object. Use
array_values()to renumber the keys when the caller expects a JSON list. PHP arrays · JSON encoding
The standard library still has different naming and argument conventions. Compare strpos($text, $term) with in_array($term, $items, true). An IDE can surface those signatures. When an awkward API appears repeatedly at an application boundary, a small function with a domain name can give callers a simpler contract. strpos · in_array
Exercise
Section titled “Exercise”Search for 'lar', 'vel' and 'xyz' in 'laravel'. Predict the three results of strpos() before running it. A correct check distinguishes 0, 4 and false.