0

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?

5
  • sorry i meant to say BEFORE i run, $blue = 0 Commented Apr 27, 2012 at 6:49
  • $blue++; ? is that what u want? correct = to == in second brackets Commented Apr 27, 2012 at 6:50
  • brian, edit your post to correct it. There's an "edit" link right below the tags. Commented Apr 27, 2012 at 6:50
  • Just read the code you posted once more, you should be able to find the mistake... Commented Apr 27, 2012 at 6:52
  • 2
    I seriously wonder though..., you managed to do it right for $red == "1" but not for $blue? Commented Apr 27, 2012 at 6:53

7 Answers 7

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

after so many hours i just couldn't see it! sometimes it takes someone else to see the simple. thanks
@brianwilsonL: I've updated the answer with a tip to avoid such bugs.
2

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

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

Comments

1

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

Comments

0

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

Comments

0

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

Comments

0

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)

Comments

0

use == or === instead of =.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.