Search code examples
phparraysintersectionarray-difference

Find intersecting values between two flat arrays as well as differences in both directions


I have 2 arrays

First array  -- array1(3,17,19,11,34,56,22,29);
Second array -- array2(4,6,12,19,59,21);

Now I would like to get 3 types of data

a) values which are present in both array for eg `19`
b) values which are not present in array1 but present in array 2 for eg `4,6,12,59,21`
c) values which are not present in array2 but present in array 1 for eg `3,17,11,34,56,22,29`

Can it be done using a single for() loop?


Solution

  • The PHP docs are your friend

    PHP has a bunch of built in functions for working with arrays

    The full list is here: http://www.php.net/manual/en/ref.array.php

    The ones you're after are array_intersect and array_diff

    Look mum, no loop!

    a) array_intersect($array1, $array2)

    b) array_diff($array1, $array2)

    b) array_diff($array2, $array1)