2

I have 2 arrays:

$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);

Is there any PHP function that does this?

$finalArray = unknown_php_function($array1,$array2);
// result: $finalArray = array(3,4,5);

It merges both arrays and removes values which aren't present in both arrays. Do I have to build a foreach cycle or is there an easier way? Thanks

2 Answers 2

10

You want array_intersect for this, basically the intersection of two sets (arrays, in this case), just like in school. :-)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that's exactly what I want. It's probably easily googlable but I didn't know the English expression intersection, teachers in my school teach in different language brb...
Yeah, that happens even if you're a native speaker of English :) This is a handy list of array functions in PHP: nl3.php.net/manual/en/ref.array.php
3

You're looking for array_intersect(). Here is a demo:

$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);

$finalArray = array_intersect($array1,$array2);
print_r($finalArray);

Outputs:

Array
(
    [2] => 3
    [3] => 4
    [4] => 5
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.