PHP: Testing whether three variables are equal

前端 未结 5 2093
情歌与酒
情歌与酒 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: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.

提交回复
热议问题