8

In PHP how can I quickly tell if all values in array are identical?

2
  • 1
    Also, a lot of these are googleable (like the current one) so there is no real need to post it as a question on stackoverflow Commented Mar 31, 2010 at 16:31
  • 2
    i disagree. the more data the better, even if the question exists already. it may not be "googleable" using the search term an user selects based on the way the user phrased the question. stackoverflow + google allow programmers to learn new techniques and get work done faster and more efficiently. Commented Jan 6, 2014 at 9:08

6 Answers 6

45

You can use the test:

count(array_unique($arr)) == 1;

Alternatively you can use the test:

$arr === array_fill(0,count($arr),$arr[0]);
Sign up to request clarification or add additional context in comments.

2 Comments

array_unique doesn't actually modify the original array. Please take a look at the PHP Manual: php.net/manual/en/function.array-unique.php
count(array_unique($arr)) == 1; was the most helpful code.
14
$results = array_unique($myArray);
if(count($results) == 1){
   // $myArray is all duplicates
}

4 Comments

Although this is a valid answer, I would also note that array_unique removes the duplicates, so this approach works if he does not need the array with all it's values.
It doesn't modify the original array ($myArray, in this case), rather it returns an array with duplicates removed.
Or, you can create a new variable with the array in it, and leave the original array alone.
@Anthony this function doesn't affect the original array. So $myArray will stay the same.
3

You could also use this check:

count(array_count_values($arr)) == 1

Comments

0
$myArray = array('1','1','1');
$results = array_unique($myArray);
if(count($results) == 1)
{
    echo"all value is duplicates";
}
else
{
    echo"all value is not duplicates";
}

Comments

-1

You can check for count(array_intersect($arr1, $arr2)) == 0

Comments

-1

Do a test run and see if all results are the same:

foreach ($array as $newarray){
    echo $newarray. '';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.