1

I have the following code:

$result = array_intersect($contacts1, $contacts2);

This generates:

Array
(
[21] => 
[22] => 
[23] => 
[24] => 
[25] => 
[26] => 
[28] => 

I have the following if statement:

if (empty($result)) { // i.e. NO INTERECTION

I just realized that this will not work as a test for no intersection because many elements are produced, all with the value null. Given this what is the best way to test for intersection of 2 arrays?

0

2 Answers 2

3

If NULLs are in the array, then array_intersect will return them as being in both arrays.

$contacts1 = array("bob", "jane", NULL, NULL);
$contacts2 = array("jim", "john", NULL, NULL);
$result = array_intersect($contacts1, $contacts2);
print_r( $result );

Array ( [2] => [3] => )

You can filter each array before the intersection using array_filter. It takes a callback function, but by default all entries equal to FALSE will be removed, including NULLs.

$result2 = array_intersect(array_filter($contacts1), array_filter($contacts2));
print_r( $result2 );

Array ( )

Use the callback if you want to specifically filter only NULLs, or what your requirements are.

function mytest($val) {
   return $val !== NULL;   
}
$result3 = array_intersect(array_filter($contacts1, "mytest"), array_filter($contacts2, "mytest"));
print_r( $result3 );

Array ( )

Sign up to request clarification or add additional context in comments.

Comments

2

You can check if all the values are null (if you know that no null's can exist in your arrays). You can use array_filter function.

For example:

$result = array_filter(array_intersect($contacts1, $contacts2));

That way, all nulls will be removed, and the result (if no intersecion exists) will be an empty array.

UPDATE: As said in the comment, this will remove also non-null values. A revised version is to use the callback function:

function filterOnlyNulls($elem) {
    return $elem !== null;
}

$result = array_filter(array_intersect($contacts1, $contacts2), "filterOnlyNulls");

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.