Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare with int and string in IF condition

Code in PHP :

<?php
    $key = 0;
    if($key == 'monty' && $key == 'anil'){
        echo 'Mackraja';
    }else{
        echo "Nothing";
    }
?>

OR

<?php
    $key = 2;
    if($key == '2abc' || $key == 'abc2'){
        echo 'Mackraja';
    }else{
        echo "Nothing";
    }
?>

OUTPUT: Mackraja

like image 470
Monty Avatar asked Feb 03 '16 09:02

Monty


People also ask

Can we compare string with int?

You can't compare them if you don't give specific criteria. If you want to compare their integer values, then you should convert the string to integer before comparing as you did with proper error handling (i.e. when the string is not an integer).

Can we compare string in if statement?

Using user-defined function : Define a function to compare values with following conditions : if (string1 > string2) it returns a positive value. i.e.(string1 == string2) it returns 0. if (string1 < string2) it returns a negative value.

Can you use == to compare strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you compare strings in if else?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.


1 Answers

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. - Source

This means that

<?php
    var_dump(0 == "a"); // 0 == 0 -> true
    var_dump("1" == "01"); // 1 == 1 -> true
    var_dump("10" == "1e1"); // 10 == 10 -> true
    var_dump(100 == "1e2"); // 100 == 100 -> true

So when you're comparing $key (with value 0) to the strings, the strings have value 0 and they both return true. This way, it will always output "Mackraja".

Changing the value of $key to any other integer will return false.


Note that

The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value. - Source

This means that changing the comparison operator to === will mean that the values have to match completely - i.e., a string 1 will not be equal to an integer 1: they have to match formats:

echo $key == 'monty' && $key == 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Mackraja"

echo $key === 'monty' && $key === 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Nothing"
like image 161
Ben Avatar answered Oct 25 '22 20:10

Ben