Skip to content
PHP Misconceptions

Chapter 12

Which PHP Quirks Still Matter?

Test comparison rules, false-or-integer results and array keys against the PHP runtime you use today.

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

Run the script from the repository root with PHP 8.6 or later.

Terminal window
php code/php-misconceptions/quirks.php
0 == "php": false
0 == "0": true
0 === "0": false
Match 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 to 0 with ==. Use === when the type is part of the comparison. The example already uses strict_types=1, which does not change the behaviour of ==. Number and string comparisons
  • Return values. strpos() returns a zero-based byte offset or false. A truthiness check treats offset zero as false. Use !== false to check whether you got a position, or str_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

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.

Does Legacy PHP Always Need a Rewrite?

Report a problem with this example