4

Forgive me if this is a common thing but I'm not sure how I should go about it.

I would like to see if three variables are identical to each other

I thought i could do this:

<?php
 if ($one == $two == $three) {
  echo "they all match.";
 } else {
  echo "one of these variables do not match."; 
 }
?>

But i guess that's not possible.

Is there a syntax for this? or do I have to check them individually/with && or || ?

I'm aware that checking them separately would give more accuracy (and is probably better practice) but for this particular situation it doesn't matter which one doesn't match.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
Partack
  • 886
  • 11
  • 24

4 Answers4

9

I would use:

if ( $one === $two && $two === $three )
    echo "they all match."
else
    echo "one of these variables do not match.";
  • #1 == #2 (no type coercion)
  • #2 == #3 (no type coercion)
  • ∴ #1 == #2 == #3
Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69
  • Thank you for the explanation at the bottom of your answer, I got it when you said it and had an 'Ah-ha!' moment, but you illustrated it wonderfully which will make it easier to remember. Thank you. (Also, fastest answer. Gratz. =) ) – Partack Aug 03 '11 at 01:04
7

Here's an alternative solution that might be helpful. It will be particularly useful if your variables are already in an array.

$a = array($one, $two, $three);

if(count(array_unique($a)) == 1){
  // all match
}
else {
  // some items do not match
}
maček
  • 76,434
  • 37
  • 167
  • 198
4

You have you use &&. Fortunately, by the transitive property of ==, you only have to check two out of three :).

if ($one == $two && $two == $three) {
    echo "they all match.";
} else {
    echo "one of these variables do not match."; 
}

Want a "do what I mean" language? Use Python.

>>> a = 'foo'
>>> b = 'foo'
>>> c = 'foo'
>>> a == b == c
True
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • hahaha, that last snippet looks fun. I'm going to learn python one of these days, just don't know when.. I've heard many good things about it ^__^ thanks for your quick response =) – Partack Aug 03 '11 at 01:01
  • 3
    Much `<3` for Python. Of course you can also do stuff like `x < y <= z` instead of `x < y and y <= z` as well. – Matt Ball Aug 03 '11 at 01:02
3

Dont think you can do it simpler then:

if ($one == $two && $two == $three)
Poul K. Sørensen
  • 16,950
  • 21
  • 126
  • 283