prgrm
prgrm

Reputation: 3833

PHP- Create an array with the matches of two arrays

I am trying to compare two non-associative arrays to create a new array with the matches.

This is what I have though:

//This array has several entries
$a_firstarray = Array();
//This array has less entries than the first array
$a_secondarray = Array();
//This array should contain the matches of the first array and the second array in no particular order
$a_mergedarray

    for($i=0;$i <=count($a_firstarray);$i++){
            for($a=0;$a <=count ($a_secondarray);$a++){
                if($a_firstarray[$i] == $a_secondarray[$a]){
                    $a_mergedarray[] = $a_activecategory[$i];
                }
            }
        }

It doesn't work for some reason. I am also sure that PHP has some sort of function that does this. Any ideas? thanks in advance.

Upvotes: 1

Views: 64

Answers (3)

rypskar
rypskar

Reputation: 2092

Are you looking for array_intersect()? http://php.net/manual/en/function.array-intersect.php

Upvotes: 1

Ravi Hirani
Ravi Hirani

Reputation: 6539

use array_intersect.

$result = array_intersect($array1, $array2);

Upvotes: 1

Jim
Jim

Reputation: 22646

This is known as the "intersection" of two arrays. PHP provides array_intersect.

Upvotes: 1

Related Questions