Take the 2-minute tour ×

I mostly use the switch case for string values. Can someone confirm if they can be used for equality of complex objects and if the objects are different too. As you can see I'm not always checking if $obj1 == some other objects. Both objects can change. Can someone tell me what would be the right syntax for this if it's allowed? I'm not sure what I would put as the switch() input itself.

if ($obj1 == $obj9) 

elseif ($obj5 == $obj9)

elseif ($obj5 == $obj1)


new code, would this be correct?

switch (true){
     case $obj1 == $obj9: 
          //do something
     case $obj5 == $obj9:
          //do something
     case $obj5 == $obj1: 
          //do something
     case default: 
          //do something
share|improve this question
Since you're comparing three objects with one another, that wouldn't fit in a switch unless you did switch(true) (which isn't what the construct was intended for). Your if-elseif-else seems to be the right way to go. –  BoltClock Jan 8 '11 at 5:12
@BoltClock, you mean like the code I added? What would happen if I used switch(true) even if that's not what was intended? –  silow Jan 8 '11 at 5:29
It will work (btw default: not case default:) nevertheless. I was just going on about how if-else would make more sense than a switch. See Kel's answer for why. –  BoltClock Jan 8 '11 at 5:31
I think, if-else is much more appropriate for such type of comparisons (switch-case introduces redundant complexity). –  Kel Jan 8 '11 at 5:35

1 Answer 1

up vote 1 down vote accepted

According to PHP Manual, switch-case statement is equal to "if" statement with "==" comparison. So, it does comparison in accordance with these rules. Objects are compared in accordance with objects comparison rules.

BTW switch-case statement is typically used to compare one value against set of several another values, while if-else construction in your question compares 3 pairs of different variables.

share|improve this answer

Your Answer


