D
D
dieselbox2011-04-13 12:57:25
PHP
dieselbox, 2011-04-13 12:57:25

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

8 answer(s)
A
Alexey Shein, 2011-04-13
@conf

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.

4
4pcbr, 2011-04-13
@4pcbr

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

W
WildZero, 2011-04-13
@WildZero

Because $b is not equal to "on"?

A
Alexey, 2011-04-13
@alexxxst

"on" converts to int -> 0 because the first argument in the comparison is also an int.

S
Sergey, 2011-04-13
@butteff

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.

C
CrazySquirrel, 2011-04-13
@CrazySquirrel

Because 0 != 'on', try $b == intval('on'), and get +

D
dieselbox, 2011-04-13
@dieselbox

Sorry, I misunderstood. "+" is displayed, although of course it should be logically "-".

S
script88, 2012-03-18
@script88

You must have confused something with something. TinyMCE is a content editor, and cms is a content management system
. If you take TinyMCE, then it is quite popular and convenient editor.
here you can see the demo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question