DEV Community

RatulAlMamun
RatulAlMamun

Posted on • Updated on

String comparisons with zero(0) in PHP

The Problem

Strange things happen when you compare any string with zero (0) in PHP. Let me show this to you first. Then we’re going to know “WHY?”

<?php
var_dump(0 == "something");        // bool (true)
Enter fullscreen mode Exit fullscreen mode

Isn’t that strange? Let me show you this strange behavior with another approach with a switch case. Cross your fingers before running this code.

<?php
switch ("something") {
case 0:
    echo "Strange";
    break;
case "something":
    echo "All is well";
    break;
}

// Strange    WTF??
Enter fullscreen mode Exit fullscreen mode

What is going on? It should print All is well, isn’t it? So, why is PHP showing this kind of output? Moreover, this kind of output can lead us to creating a bug in our code. Quite often this kind of bug happens where the comparison is implicit, such as in_array() or switch statements like in the above code. Let’s see what happend in in_array() situation:

<?php
$languages = ["C", "C++", "PHP",];
$value = 0;
var_dump(in_array($value, $languages));         // bool(true)
Enter fullscreen mode Exit fullscreen mode

The Happening

Did you watch the movie The Happening released in 2008? The story is about a mysterious toxic air, causes people to kill themselves. Let's not talk about the movie, right now we need to talk about the happenings of the toxic code. So, how did this happen in PHP?

In PHP, when a string compares with a number, the string is converted to number, due to php’s non-strict comparison semantics. In strict mode that means when we use === the type and value are compared but in non-strict mode (==) just value will be compared. In that case the type of the values are converted into integers. That's the process of how php executes. So, Let's check which string converted to what.

<?php
var_dump((int) "0");                // int(0)
var_dump((int) "01");               // int(1)
var_dump((int) "10");               // int(10)
var_dump((int) "something");        // int(0)
Enter fullscreen mode Exit fullscreen mode

There’s the magic of implicit conversion. Now we know numeric strings convert into integers but when it comes to ordinary strings it converts into zero (0). When “something” converts into zero (0) as we see, the value becomes equal so the output of “something” == 0 is became true.

The Saviour

Now it’s time to introduce The Saviour which is PHP 8. PHP 8 solves this problem with the proper rules. From now on when it comes to implicit conversion of string to numeric PHP first check on whether the string is a numeric string or not. If it’s a numeric string then the string converts into numeric, otherwise it returns false.

0 == something             // false  [in php 8]
0 == something             // true   [in php 7]
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)