PHP comparison '==' problem
Why is the output 'in'?
<?php
if (开发者_开发知识库1=='1, 3')
{
echo "in";
}
?>
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.
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.
You are comparing a string and an integer. The string must be converted to an integer first, and PHP converts numeric strings to integers. Since the start of that string is '1', it compares the number one, with the number one, these are equal.
What functionality did you intend?
If you're trying to check if 1 is equal to 1 or 3, then I would definitely do it this way:
if (1 == 1 || 1 == 3)
Please refer to the PHP documentation:
http://php.net/manual/en/language.operators.comparison.php
The output should be:
in
From PHP's documentation:
When converting from a string to an integer, PHP analyzes the string one character at a time until it finds a non-digit character. (The number may, optionally, start with a + or - sign.) The resulting number is parsed as a decimal number (base-10). A failure to parse a valid decimal number returns the value 0.
I'm guessing you want to know whether a variable is in a range of values.
You can use in_array
:
if (in_array(1, array(1, 3, 5, 6)))
echo "in";
if(in_array(1, array(1,3)) {
echo "in";
}
精彩评论