I need to check if all values in an array equal the same thing.
For example:
$allValues = array(
'true',
'true',
'true',
);
If every value in the array equals 'true'
then I want to echo 'all true'
. If any value in the array equals 'false'
then I want to echo 'some false'
Any idea on how I can do this?
If your array contains actual booleans (or ints) instead of strings, you could use
array_sum
:http://codepad.org/FIgomd9X
This works because
TRUE
will be evaluated as1
, andFALSE
as0
.Technically this doesn't test for "some false," it tests for "not all true." But it sounds like you're pretty sure that the only values you'll get are 'true' and 'false'.
All values equal the test value:
or just test for the existence of the thing you don't want:
Prefer the latter method if you're sure that there's only 2 possible values that could be in the array, as it's much more efficient. But if in doubt, a slow program is better than an incorrect program, so use the first method.
If you can't use the second method, your array is very large, and the contents of the array is likely to have more than 1 value (especially if the value is likely to occur near the beginning of the array), it may be much faster to do the following:
Note: Some answers interpret the original question as (1) how to check if all values are the same, while others interpreted it as (2) how to check if all values are the same and make sure that value equals the test value. The solution you choose should be mindful of that detail.
My first 2 solutions answered #2. My
isHomogenous()
function answers #1, or #2 if you pass it the 2nd arg.Another option:
Usage:
Also, you can condense goat's answer in the event it's not a binary:
to