Check if the values of an array are all equal PHP?

0

I would like to check if all the values in my array are the same and I did it as follows:

$minha_lista = array('a','a','a');

if(!empty($minha_lista)) {
    if(count(array_unique($minha_lista))===1){
             return true;
        } else { return false; }
    }

Unfortunately I can not get the result you want.

Is there another way to proceed?

    
asked by anonymous 06.12.2016 / 12:29

3 answers

3

There are a few ways to do this, for example:

if(count(array_unique($minha_lista))){
    //...
}

or even:

if($minha_lista === array_fill(0,count($minha_lista),$minha_lista[0])){
    //...
}

Here the function documentation: array_unique , array_fill

    
06.12.2016 / 12:39
4

You can do with a loop, like this:

$arr = ['aaa', 'aaa', 'aaa'];
$status = true;

foreach($arr as $value) {
    if($arr[0] != $value) {
         $status = false;
         break;
    }
}

The variable $status starts with true and if during loop with array is found a different value, it changes to false

    
06.12.2016 / 12:39
3

Your code is correct. I left it more "explicit", take a look:

$check_array = ('a', 'a', 'a');

$result_array = array_unique($check_array);

if (count($result_array) == 1)
   echo "Valores iguais...";
else
   echo "Valores diferentes...";
    
06.12.2016 / 12:40