+4 conditional-operator php Yosef Dec 16 '10 ...">

Problem comparing PHP with '=='

Why is the output "in"?

<?php if (1=='1, 3') { echo "in"; } ?> 
+4
source share
8 answers

Because PHP performs type conversion, it turns a string into an integer, and its methods of operation are such that they count all numbers down to a non-numeric value. In your case, a substring ('1') (because , is the first non-numeric character). If the line starts with anything but a number, you will get 0.

+3
source

The == operator performs a conversion on two values ​​to try to make them the same. In your example, it converts the second value from the string to an integer, which will be 1 . This is obviously equal to the value you match.

If your first value was a string, i.e. '1' in quotation marks, not an integer, then the match would fail, since both sides were strings, so he would do a string comparison and they would be different strings.

If you want an exact match operator that does not perform type conversion, PHP also offers a triple equal operator, === , which might be what you are looking for instead.

Hope this helps.

+5
source

You are comparing a string and an integer. First, the string must be converted to an integer, and PHP will convert the numeric strings to integers. Since the beginning of this line is "1", it compares number one with number one, they are equal.

What functionality did you intend?

+4
source

If you are trying to check if 1 1 or 3 is equal, I would definitely do it like this:

 if (1 == 1 || 1 == 3) 
+1
source

I assume you want to know if a variable is in a range of values.

You can use in_array :

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

The output should be:

 in 

From the PHP documentation:

When converting from a string to an integer, PHP parses a single character string until it finds an asymmetric character. (A number may optionally begin with a + or - sign.) The resulting number is analyzed as a decimal number (base-10). Failure to parse a valid decimal value to 0.

-1
source

Source: https://habr.com/ru/post/1332381/


All Articles