phparraysvalidationfilter

How to determine if an array contains anything but a specific value?


Given the below array of values, what is the best way to determine if the array contains anything other than the value 4?

$values = [1,2,3,4,5,6];

For clarity, I don't want to check that 4 simply doesn't exist, as 4 is still allowed to be in the array. I want to check the existence of any other number.

The only way I can think to do it is with a function, something like the below:

function checkOtherValuesExist(array $values, $search) {
  foreach ($values as $value) {
    if ($value !== $search) 
      return TRUE;
    }
  }
}

Solution

  • TBH - I think your current version is the most optimal. It will potentially only involve 1 test, find a difference and then return.

    The other solutions (so far) will always process the entire array and then check if the result is empty. So they will always process every element.

    You should add a return FALSE though to make the function correct.