Reputation: 41
I want to check in a single statement, if the contents of array are same or not. This is actually a challenge for me, but I am not able to check for the uniqueness of the values inside an array.
Also I want to make sure that the values are same as, say "S"
. Example array:
$myArray = array("S", "S", "S"); // true
$myArray = array("S", "S", "s"); // false
Is it possible using a single statement? Thanks in advance.
Upvotes: 3
Views: 68
Reputation: 167172
Yes, possible with array_count_values
. Is this what you are looking for?
The function array_count_values()
will count the number of unique values in the array. If you get the count of it to be 1
, it is then unique like you said.
count(array_count_values($myArray)) == 1
Also, you can check one of the array values to be whatever value you wanted to check.
$myArray[0] == "S"
So combining these two in a single condition:
count(array_count_values($myArray)) == 1 && $myArray[0] == "S"
This will return true
or false
.
Full Working Code
<?php
// Let's have two arrays.
$myArray1 = array("S", "S", "S"); // Should return true
$myArray2 = array("S", "S", "s"); // Should return false
// Our function
function checkArray($theArray, $value) {
return count(array_count_values($myArray)) == 1 && $myArray[0] == $value;
}
// Checks
checkArray($myArray1, "S"); // true
checkArray($myArray2, "s"); // false
Upvotes: 2