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");
  1. bool(true)
    bool(true)
    bool(true)
    bool(true)
  2. bool(false)
    bool(true)
    bool(true)
    bool(true)
  3. bool(false)
    bool(false)
    bool(false)
    bool(true)
  4. 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.