user610983
user610983

Reputation: 855

PHP Return result in different group

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

Upvotes: 3

Views: 93

Answers (4)

Alin P.
Alin P.

Reputation: 44346

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.

Upvotes: 4

codaddict
codaddict

Reputation: 455332

$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

Upvotes: 0

Dmitri Gudkov
Dmitri Gudkov

Reputation: 2133

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

Upvotes: 0

Chris Laarman
Chris Laarman

Reputation: 1597

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

Upvotes: 0

Related Questions