Partack
Partack

Reputation: 886

PHP: The best way to check if 3 variables are identical?

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.

Upvotes: 4

Views: 4927

Answers (4)

maček
maček

Reputation: 77778

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
}

Upvotes: 7

Poul K. S&#248;rensen
Poul K. S&#248;rensen

Reputation: 17530

Dont think you can do it simpler then:

if ($one == $two && $two == $three)

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359786

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

Upvotes: 4

Jon Gauthier
Jon Gauthier

Reputation: 25572

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

Upvotes: 9

Related Questions