comparing a string, and, a string with only numbers
I am new to php and have been trying with no success to get this comparison working:
I have a variable 'productCode' that might hold
I need to know what is in the variable productCode? Is it still 'Choose' or '102' (like string with only numbers)
What comparison operator should I use?
Is it having the value 'Choose'? It should be
I tried
if(strcmp($productCode,'Choose')){
}//tried double quotes also
if(($productCode=='Choose')){
}//tried double quotes also
if(($productCode==='Choose')){
}//tried double quotes also
I am stumbled at this.. '102' compared with 'Choose' is also passing the if statement...
Can someone please help me with a correct method of checking this mixed case..
Edit 1: The related code (after incorporating the === 0 suggesion by Rizier123 :
$productCode11=$_POST['productCode11'];
$productCode12=$_POST['productCode12'];
$productCode13=$_POST['productCode13'];
if(strcmp($productCode11,'Choose') === 0){
//testing the values if they actually hold what I am expecting
echo '<script type="text/javascript">alert(" '.$productCode11.' ");</script>';
echo '<script type="text/javascript">alert(" '.$productCode12.' ");</script>';
//testing if the 'if' check passes
echo '<script type="text/javascript">alert("same");</script>';
$productCode11Error="Fill This";
$incomplete=true;
}
if(strcmp($productCode12,'Choose') === 0)){
$productCode12Error="Fill This";
$incomplete=true;
}
if(strcmp($productCode13,'Choose') === 0){
$productCode13Error="Fill This";
$incomplete=true;
}
Edit 2 I did some tests and these are the strange results I got:
$test = strcmp($productCode11, 'Choose');
$test2 = strcmp($productCode11, $productCode12);
if both are 'Choose' I get 1 and it is incremented by 1 for every submission (2,3,4,5...)
if both are numbers and same, I get 0
if LHS is number and RHS is 'Choose', I get -1
if LHS and RHS are 'Choose' I get 1,3,4..
if LHS is 'Choose' and RHS is number I get 1
if both are numbers, and LHS > RHS I get 1
if both are numbers and RHS > LHS I get -3
Your first attempt just works as it should. But you have to know, that strcmp()
return 0, when the strings are equal, so just add a comparison, eg
if(strcmp($productCode, 'Choose') === 0) {
//^^^^^ See here
}
So with this it will evaluate as TRUE if $productCode
is equal to "Choose"
.
Sidenote:
strcmp()
is case-sensitive, means: aA != aa
strcasecmp()
is case-insensitive, means aA == aa
After a long trial and error, I suspected that the variables returning from $POST are probably having some extra characters. To address this I tried using trim()
function. Surprisingly everything started working 'AS EXPECTED'.
(And I am sticking to the === 0 suggestion by Rizier123)
链接地址: http://www.djcxy.com/p/58588.html上一篇: 检查是否可以比较PHP对象
下一篇: 比较一个字符串和一个只有数字的字符串