1

Array declaration: $uids = array();

Next these arrays may or may not be created:

$uids['locations'];
$uids['ages'];
$uids['genders'];

If at least 2 of them are created I want to calculate the intersect. If all 3 are created I want the intersect of all 3.

So, I may want to calculate the intersect of $uids['locations'] and $uids['ages'] or the intersect of $uids['ages'] and $uids['genders'], etc.

If put all 3 arrays in array_intersect then I get errors if one of them is not an array. I'm not sure how to handle this without an awful lot of if:else statements and think there is a better way.

1 Answer 1

5

If you know that you don't have more array keys than the ones specified, you can use this:

$intersect = array();
if (count($uids) > 1) {
    $intersect = call_user_func_array('array_intersect', $uids);
}

Otherwise you could try this one:

$_uids = array_intersect_key($uids, array(
    'locations' => 1,
    'ages' => 1,
    'genders' => 1,
));
if (count($uids) > 1) {
    $intersect = call_user_func_array('array_intersect', $_uids);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@soulmerge: great solution, +1! But in this case we cannot specify which items to intersect

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.