Check some array values within another array

Asked

Viewed 43 times

2

I need to test if an array has some values that are mandatory by comparing within another array, I currently count the required values, open a loop, and check if the checked values 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 of the first array are required in the second.

The array is one-dimensional.

1 answer

1


I suggest using the function array_intersect which gives you the interjection 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

Wouldn’t it be better to return false also when it’s not valid ? It’s strange a method that returns boolean only to be able to return true and never false. The code would be much simpler:

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

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

Has also array_intersect_key if you want to calculate the interjection based only on the key, assuming that each element of the array has key and value.

  • I didn’t know this function, a much better solution, I just can’t drop a boleano because I need a precise treatment of this false, the code ta mto encapsulated ai will be complicated to treat the exceptions with false where it is called, but solved! obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.