PHP Return result in another group

all

I have a dataset of type 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

then I divide this data into 2 groups, which

$groupA = range(1, 5)

$groupB = range(6, 10)

For example, I have $data = array(1, 4), and he will return it to group A. Similarly,, $data = array(7,8)he will return to me Group B.

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

thank

+3
source share
4 answers

You can 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 tofalse , while one with at least one element evaluates to true.

. , . array_intersect , .

+4

- ?

$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

0

Try using array_intersect with each group ... if the intersection is not null, it means that some elements are in this group ...

0
source
$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);      
}

Take a look

0
source

All Articles