PHP: Testing whether three variables are equal

前端 未结 5 2090
情歌与酒
情歌与酒 2021-02-06 21:43

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 co

相关标签:
5条回答
  • 2021-02-06 21:52

    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.

    0 讨论(0)
  • 2021-02-06 21:55

    I had a unique situation in which I needed to see if the amount of items in three arrays was the same much like this scenario.

    This is what I came up with:

    (Assume that fields, operators and values are all arrays)

    $allfieldscount = array(count($fields), count($operators), count($values)); //store an array of the count of all the arrays.
    
    $same = array_count_values($allfieldscount);//returns an array by values in the array.  We are looking to see only 1 item in the array with a value of 3.
    
    if(count($same) != 1){
        //Then it's not the same
    }else{
       //Then it's the same
    }
    

    This tactic counts the fields in the different arrays and by using array_count_values if they are all the same then the count of the array it returns will be '1', if it's anything else then it's not the same. Look up array_count_values on php.net to understand more what its doing.

    0 讨论(0)
  • 2021-02-06 21:57
    $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.

    0 讨论(0)
  • 2021-02-06 22:02
    if ((a == b) && (b == c)) {
       ... they're all equal ...
    }
    

    by the transitive relation

    0 讨论(0)
  • 2021-02-06 22:06
    if ($select_above_average === $select_average
        && $select_average === $select_below_average) { }
    
    0 讨论(0)
提交回复
热议问题