Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Testing whether three variables are equal

I've never come across this before, but how would you test whether three variables are the same? The following, obviously doesn't work but I can't think of an elegant (and correct) way to write the following:

if ($select_above_average === $select_average === $select_below_average) { }

like image 755
Matty Avatar asked Jan 15 '11 23:01

Matty


People also ask

How do you know if three variables are equal?

To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.

What is == and === in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. Syntax: operand1 == operand2. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

What does 3 equal signs mean in PHP?

The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false.


4 Answers

if ((a == b) && (b == c)) {
   ... they're all equal ...
}

by the transitive relation

like image 116
Marc B Avatar answered Oct 07 '22 17:10

Marc B


$values = array($select_above_average, $select_average, $select_below_average);

if(count(array_unique($values)) === 1) {
    // do stuff if all elements are the same
}

Would be another way to do it.

like image 36
PeeHaa Avatar answered Oct 07 '22 17:10

PeeHaa


if ($select_above_average === $select_average
    && $select_average === $select_below_average) { }
like image 10
Dogbert Avatar answered Oct 07 '22 16:10

Dogbert


you already have your answer by Adam but a good way to remember how to do this correctly is to remember for a single validation you should be wrapping in () braces, if your only doing one single check then you already have the braces provided by the if ( ) statement.

Example:

if ( a === b )

and if your doing multiple then

if( ( a === b ) && ( c === d ) )

Sop if you remember that every set of braces is a validation check, you can have login like this:

if( (( a === b ) || ( c === d )) && ( e === f ) )

if statements and many other logical operations work on hierarchy so that the amount of individual checks within a check has an effect on he parent check.

taking the third example above if a === b or c === d fails then e === f will never be checked as the ab,cd is wrapped in braces so that is returned and checked.

Hope this helps you a little more.

like image 6
RobertPitt Avatar answered Oct 07 '22 16:10

RobertPitt