PDA

View Full Version : Why does PHP do this?


Uranium-235
09-17-2002, 03:27 PM
ok. Gryph and someone else I know can't figure out why this is...

but from what I can tell PHP has a bad tendancy to reverse the logical operator when if the two compairson statements use not. for instance...


if(substr($domain_array[$i], 0, 1) != "#" && substr($domain_array[$i], 0, 1) != "\n")


now the substr($domain_array[$i], 0, 1) can be eather "#" or "\n" but not both. So a OR statement would be used.

However when ever I use an OR statement it does not work (false every time)

so when I Switch and use an AND statement it works just fine. (but it shouldnet, right?)

?

nex
09-17-2002, 03:52 PM
Wow, I screwed that one up.

*boards the short bus*

Grizzly
09-17-2002, 04:19 PM
This really isn't an issue of precedence, you're just not thinking very clearly.
Let's put your code into "pseudocode" terms:

IF Variable does not equal "#" AND Variable does not equal "\n"


...this statement will evaluate as "TRUE", when "Variable" equals ANYTHING other than "#" or "\n"
if you used OR instead of AND...


IF Variable does not equal "#" OR Variable does not equal "\n"


...this statement will always evaluate as "TRUE." "Variable" can only equal ONE thing at a time. So when you say: "IF Variable does not equal this, or Variable does not equal that"...you're putting yourself in a corner. "Variable" will always be NOT EQUAL to one of the two.

...I think what you want to be saying is:

IF Variable equals "#" OR Variable equals "\n"

//...or in other words
if(substr($domain_array[$i], 0, 1) == "#" || substr($domain_array[$i], 0, 1) == "\n"))


Make sense?

Grizzly
09-17-2002, 04:27 PM
Originally posted by nex

&& and || take precedence over !=


Wrong. PHP.net specifically said: "with the lowest-precedence operators listed first." So && and || are LOWER precedence than !=, just like any other C-style language.

Uranium-235
09-17-2002, 05:31 PM
ohh I see

*boards the short bus with nex*

Grizzly
09-17-2002, 05:44 PM
Originally posted by Uranium-235
*boards the short bus with nex*

Rofl!!! I haven't heard that term "short bus" in a long time. Back when I was a little tike, my less-politically-correct friends affectionately refered to it as the "tard cart." Ahhhh memories.