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
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).
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With