Check that the values of an array are all the same PHP?

Asked

Viewed 2,196 times

0

I would like to check that all values in my array are equal and I did so :

$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’t get the desired result.

There is another way to proceed ?

  • 1

    But apparently if code is right, what’s wrong or what he doesn’t do?

  • your code is correct, you don’t need anything! only if you have something you’re not reporting in your question ... !!!

  • @André-pka Is there any other problem that is occurring? Because as the friend above said... Your code is correct.

3 answers

4

You can do it 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 begins as true and whether during the loop with the array is found some different value, it changes to false

3


There are some ways to do this check, for example:

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

or even:

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

Here the documentation of the functions: array_unique, array_fill

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...";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.