3

all

I have a bundle of data like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

then I separate these data into 2 groups which is

$groupA = range(1, 5)

$groupB = range(6, 10)

For instance, I have $data = array(1, 4) and it will return this belong to Group A. Likewise, $data = array(7,8), it will return to me Group B.

So how can I write a script to let $data = array(1, 4, 6, 7) return me Group A and Group B?

Thank you

0

4 Answers 4

4

You may want to use array_intersect:

$groupA = range(1, 5);
$groupB = range(6, 10);
$data = array(1, 4, 6, 7);
$foundGroups = array();
if(array_intersect($data, $groupA))
    $foundGroups[] = 'A';
if(array_intersect($data, $groupB))
    $foundGroups[] = 'B';
print_r($foundGroups);

Note that an empty array evaluates to false while one with at least one element evaluates to true.

Warning: If you have to work with a lot of groups with many elements you may want to use a manual approach and stop at the first common element found. array_intersect finds all the common elements and you don't really need that.

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

2 Comments

clean solution. but not efficient for large arrays. It does full intersection even if checking first value shows that the subarray belongs to larger array.
@DhruvPathak You are right. A manual approach would be more efficient on larger arrays. Maybe even a sorting of the groups and the data before search begins. But this depends on his scenario. What I posted is a clean solution for relatively small data sets.
0

Do you mean something like this?

$data = array(1, 4, 6, 7)
$groupA = array();
$groupB = array();

foreach ((array) $data as $value) {
    if ($value < 6) {
        $groupA[] = $value;
    } else {
        $groupB[] = $value;
    }
}

Greetz,

XpertEase

Comments

0

Try to use array_intersect with every group... if the intersection in not null it means that some elements are in this group...

Comments

0
$data = range(1,9);

$groupA = array_filter($data, "less");
$groupB = array_filter($data, "more");


function less ($v) {
        return $v < 6;
}

function more ($v) {
        return ! less($v);      
}

See it

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.