Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP comparison '==' problem

Why is the output 'in'?

<?php
    if (1=='1, 3')
    {
        echo "in";
    }
?>
like image 924
Ben Avatar asked Dec 16 '10 17:12

Ben


Video Answer


2 Answers

The == operator does type conversion on the two values to try to get them to be the same type. In your example it will convert the second value from a string into an integer, which will be equal to 1. This is then obviously equal to the value you're matching.

If your first value had been a string - ie '1' in quotes, rather than an integer, then the match would have failed because both sides are strings, so it would have done a string comparison, and they're different strings.

If you need an exact match operator that doesn't do type conversion, PHP also offers a tripple-equal operator, ===, which may be what you're looking for instead.

Hope that helps.

like image 157
Spudley Avatar answered Sep 22 '22 09:09

Spudley


Because PHP is doing type conversion, it's turning a string into an integer, and it's methods of doing so work such that it counts all numbers up until a non-numeric value. In your case that's the substring ('1') (because , is the first non-numeric character). If you string started with anything but a number, you'd get 0.

like image 36
Rudu Avatar answered Sep 18 '22 09:09

Rudu