Answer the question
In order to leave comments, you need to log in
Type conversion in PHP
Here is the code:
But as a result we get the answer "+". The question is simple - why?
$b=0;
if($b=="on") {
echo "+";
}
else {
echo "-";
}
Answer the question
In order to leave comments, you need to log in
Let's start with the fact that your code still displays + and not -.
If $b = 0 (int, integer type), then with a non-strict comparison with the string “on”, it is converted to an integer type, which means it will become zero (see paragraph 3) , from which the condition with the plus output will work.
If $b = "0" (string), then in case of non-strict comparison with the string "on", types will not be cast, because they already match, and since the strings are not equal to each other, then the condition with the output of a minus will work.
It is necessary to take into account the fact that in $_GET and $_POST all values are strings (well, or arrays of strings), which means that the rules for converting types from strings will work.
"on" converts to int -> 0 because the first argument in the comparison is also an int.
variable b contains zero.
in the condition compared, if b = on (and it is not equal), then there will be a plus on the screen.
But it is not equal, because there is zero, so minus.
PHP does not need to convert types.
if there is a number, then this is a number, you can add, subtract, divide.
if string is a string.
he himself will understand what is inside, except for rare moments.
Sorry, I misunderstood. "+" is displayed, although of course it should be logically "-".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question