Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine 2 Arrays of Different Lengths [duplicate]

Tags:

arrays

php

I have two arrays, each of different counts, the example I'm working with is there's 132 in one and 136 in the other,

I need to array_combine() them (make the first one the key, and the second one the value). In my example I would like to keep 132 key/value pairs and drop of the extra 4 that have no corresponding match.

I have currently got this function (which I found on php.net's docs of array_combine()), but it isn't working:

function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
     }

I keep getting back

Warning: array_combine() [function.array-combine]: Both parameters should have an equal number of elements on the line that starts with $arr4[] = ...

Any advice would help,

thanks!

like image 721
Doug Molineux Avatar asked Jan 22 '11 17:01

Doug Molineux


2 Answers

function array_combine2($arr1, $arr2) {
    $count = min(count($arr1), count($arr2));
    return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}
like image 85
Arnaud Le Blanc Avatar answered Sep 19 '22 00:09

Arnaud Le Blanc


Here is a one-liner:

$res = array_combine(array_intersect_key($arr1, $arr2), array_intersect_key($arr2, $arr1));
like image 45
Shumoapp Avatar answered Sep 19 '22 00:09

Shumoapp