In PHP how can I quickly tell if all values in array are identical?
2
-
1Also, a lot of these are googleable (like the current one) so there is no real need to post it as a question on stackoverflowSeanJA– SeanJA2010-03-31 16:31:16 +00:00Commented Mar 31, 2010 at 16:31
-
2i 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.zeros-and-ones– zeros-and-ones2014-01-06 09:08:23 +00:00Commented Jan 6, 2014 at 9:08
Add a comment
|
6 Answers
You can use the test:
count(array_unique($arr)) == 1;
Alternatively you can use the test:
$arr === array_fill(0,count($arr),$arr[0]);
2 Comments
St. John Johnson
array_unique doesn't actually modify the original array. Please take a look at the PHP Manual: php.net/manual/en/function.array-unique.phprisingPhoenix1979
count(array_unique($arr)) == 1; was the most helpful code.$results = array_unique($myArray);
if(count($results) == 1){
// $myArray is all duplicates
}
4 Comments
Anthony Forloney
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.brettkelly
It doesn't modify the original array (
$myArray, in this case), rather it returns an array with duplicates removed.Cryophallion
Or, you can create a new variable with the array in it, and leave the original array alone.
St. John Johnson
@Anthony this function doesn't affect the original array. So $myArray will stay the same.