PHP 8.0: Non-strict Comparisons for a String and a Number

Non-strict comparisons in PHP are always not easy to work with, and here is the last piece of this common issue:

  • PHP < 8.0: “one operand is a number and the other one is a numeric string, then the comparison is done numerically”.
  • PHP >= 8.0: “Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings.”

This leads to opposite results for this code:

var_dump( 'not_valid' <= 1);

Output for 8.0.0 – 8.0.3
bool(false)

Output for 7.3.0 – 7.3.28, 7.4.0 – 7.4.16
bool(true)

Ref: https://3v4l.org/A5agd

A simple solution is to cast the string value to integer:

var_dump( (int) 'not_valid' <= 1);

Here is the result:

Output for 4.3.0 – 4.3.11, 4.4.0 – 4.4.9, 5.0.0 – 5.0.5, 5.1.0 – 5.1.6, 5.2.0 – 5.2.17, 5.3.0 – 5.3.29, 5.4.0 – 5.4.45, 5.5.0 – 5.5.38, 5.6.0 – 5.6.40, 7.0.0 – 7.0.33, 7.1.0 – 7.1.33, 7.2.0 – 7.2.34, 7.3.0 – 7.3.28, 7.4.0 – 7.4.16, 8.0.0 – 8.0.3

bool(true)

https://3v4l.org/7aZA9

Follow-up

I am adding this PR to improve PHP Manual regarding this issue:

https://github.com/php/doc-en/pull/602

Relevant links:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s