brian wilson
brian wilson

Reputation: 495

php if and statement causing problems

Im trying to test a validation using an if statement.

if (($red == "1") && ($blue = "1") ) { $green = "hello"; }

Before this statement runs $blue = 0.

After i run this... $blue changes to 1.

Any ideas why?

Upvotes: 0

Views: 943

Answers (7)

arun
arun

Reputation: 3677

use == or === instead of =.

the '=' is assignment operator, the conditional operators are == or ===

if (($red == "1") && ($blue == "1") ) 
 { 
     $green = "hello"; 
 }

Upvotes: 0

codaddict
codaddict

Reputation: 455282

You are using = in place of ==:

if (($red == "1") && ($blue = "1") ) { $green = "hello"; }
                           ^^^

As a result (assuming the left side of && returns true) $blue gets assigned "1".

It's one of the most common programming mistakes!! As a way to prevent it from happening programmers put the constant on the left hand side of the the == as:

1 == $blue

so that if by mistake you end up writing = in place of == :

1 = $blue

you get a syntax error as you cannot assign to a constant.

Upvotes: 6

Jobin
Jobin

Reputation: 8282

Try this if (($red == "1") && ($blue == "1") ) { $green = "hello"; }

//your code is ($blue ="1") '=' is an assignment operator in php comparison is '=='

Upvotes: 2

vvr
vvr

Reputation: 466

you are assigning $blue = 1 instead of comparing that's why $blue is 1

Upvotes: 1

ehanoc
ehanoc

Reputation: 2217

Yeah use == instead of =

I would go further and say that maybe you should put literals on the left hand when comparing to avoid such situations.

Like if(1 == $blue) instead of if($blue == 1)

Upvotes: 0

Shaikh Farooque
Shaikh Farooque

Reputation: 2640

Your equal to sing is incorrect in next condistions if (($red == "1") && ($blue == "1") ) { $green = "hello"; }

Upvotes: 0

Florin Ghita
Florin Ghita

Reputation: 17643

This is because you use =. Use $blue == "1".

Upvotes: 0

Related Questions