0

I have 2 arrays which might look something like this:

$a1 = array('c','b','a');
$a2 = array('a', 'b', 'c', 'd', 'e');

I need to somehow check whether every value in $a1 is present in $a2.

I've looked at array_diff and array_intersect but can't see how they can be used because the only return the values that are present and not present respectively.

4 Answers 4

2

I am not sure what you mean by "present respectively" but array_diff is the function you are looking for. Just make sure you pass the arrays into the function in the correct order. Try:

// result = no
echo count( array_diff( $a1, $a2 ) ) ? 'yes' : 'no';
// result = yes
echo count( array_diff( $a2, $a1 ) ) ? 'yes' : 'no';
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for, thank you! I guess I was passing them in the wrong order when I first tried it
1

Look at this:

http://php.net/manual/de/function.in-array.php

Okay, I'll make it clearer:

The Function in_array() gives you a Boolean if the needle is in the haystack. So, a line like this will work for you:

$return = in_array($a1, $a2, true);

If $a1 is in $a2 the function returns true, otherwise false. The third Parameter activates strict search, so there won't be return even when a false would be right.

1 Comment

Since PHP 4.2 in_array() takes array for all parameters.
0

You can use something like

sizeof(array_intersect($a1, $a2)) == sizeof($a1)

Comments

0
function has_all_values($base, $comparing) {
    foreach($comparing as $value) {
        if(!in_array($base, $value))
            return false;
    }
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.