Check some array values inside another array

2

I need to test if an array has some values that are mandatory comparing inside another array, I currently count the required values, loop, and check if the values checked were in the same amount:

    private function validate_required($data, $required) {
        $c = count($required);
        $a = 0;
        foreach ($data as $key) {
            if (in_array($key, $required)) {
                $a += 1;
            }
        }
        if ($a != $c) {
            throw new \Exception('O elemento {elemento} não possui todos os atributos obrigatórios', 'ex0893');
        }
        return true;
    }
  

What would be a more natural way to do this test?

OBS :

Not all values in the first array are mandatory in the second array.

The array is one-dimensional.

    
asked by anonymous 24.03.2018 / 01:42

1 answer

1

I suggest using the array_intersect function that gives you the inter- est of two arrays. For the case in question if the intersection results in the input array then all elements of $required exist in $data :

private function validate_required($data, $required) {
    $inBoth = array_intersect($data, $required);
    if (count($inBoth) !== $c) {
        throw new \Exception('O elemento {elemento} não possui todos os atributos obrigatórios');
    }
    return true;
}

See this example working on Ideone

Would not it be better to return false also when it is not valid? It is strange that a method that returns Boolean can only return true and never false . The code would look even simpler:

private function validate_required($data, $required) {
    $inBoth = array_intersect($data, $required);
    return count($inBoth) === $c;
}

In addition I would also avoid having to call the method within a try catch because I would no longer throw an exception.

You also have array_intersect_key if you want to calculate the interest only based on the key , assuming each array element has key and value.

    
24.03.2018 / 02:12