Check if all values in array are the same

2020-01-29 05:00发布

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?

标签: php arrays
8条回答
贪生不怕死
2楼-- · 2020-01-29 05:54

Why not just compare count after calling array_unique()?

To check if all elements in an array are the same, should be as simple as:

$allValuesAreTheSame = (count(array_unique($allvalues)) === 1);

This should work regardless of the type of values in the array.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-29 06:00

You can compare min and max... not the fastest way ;p

$homogenous = ( min($array) === max($array) );
查看更多
登录 后发表回答