5

Why is the output 'in'?

<?php
    if (1=='1, 3')
    {
        echo "in";
    }
?>
2

8 Answers 8

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

4

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?

1 Comment

I would also like to add that if he had used the "===" (identity comparison) he would have compared the type as well.
1

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)

Comments

1

Please refer to the PHP documentation:

http://php.net/manual/en/language.operators.comparison.php

Comments

0

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.

1 Comment

+1 to cancel the -1 since you did explain why the effect was happening (at least have pertinent info)...
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";

Comments

0
if(in_array(1, array(1,3)) {
    echo "in";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.