Question

I have two arrays (in PHP):

ArrayA
(
    [0] => 9
    [1] => 1
    [2] => 2
    [3] => 7
)

ArrayB
(
    [0] => 1
    [1] => 1
    [3] => 8
)

I want to make two new arrays, where I have only the elements declared in both of the arrays, like the following:

ArrayA
(
    [0] => 9
    [1] => 1
    [3] => 7
)

ArrayB
(
    [0] => 1
    [1] => 1
    [3] => 8
)

In this example ArrayA[2] doesn't exist, so ArrayB[2] has been unset.

I wrote this for loop:

for ($i = 0, $i = 99999, $i++){
    if (isset($ArrayA[$i]) AND isset($ArrayB[$i]) == FALSE)
    {
        unset($ArrayA[$i],$ArrayB[$i]);
    } 
}

But it's not great because it tries every index between 0 and a very big number (99999 in this case). How can I improve my code?

Was it helpful?

Solution

The function you're looking for is array_intersect_key:

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

Since you want both arrays, you'll have to run it twice, with the parameters in opposite orders, as it only keeps keys from the first array. An example:

$arrayA_filtered = array_intersect_key($arrayA, $arrayB);
$arrayB_filtered = array_intersect_key($arrayB, $arrayA);

Also, although a for loop wasn't ideal in this case, in other cases where you find yourself needing to loop through sparse array (one where not every number is set), you can use a foreach loop:

foreach($array as $key => $value) {
    //Do stuff
}

OTHER TIPS

One very important thing to note about PHP arrays is that they are associative. You can't simply use a for loop, as the indices are not necessarily a range of integers. Consider what would happen if you applied this algorithm twice! You'd get out of bounds errors as $arrayA[2] and $arrayB[2] no longer exist!

I would iterate through the arrays using nested foreach statements. I.e.

$outputA = array();
$outputB = array();
foreach ($arrayA as $keyA => $itemA) {
    foreach ($arrayB as $keyB => $itemB) {
        if ($keyA == $keyB) {
            $outputA[$keyA] = $itemA;
            $outputB[$keyB] = $itemB;
    }
}

This should give you two arrays, $outputA and $outputB, which look just like $arrayA and $arrayB, except they only include key=>value pairs if the key was present in both original arrays.

foreach($arrayA as $k=>$a)
    if (!isset($arrayB[$k]))
        unset($arrayA[$k];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top