How to find the intersection (same values) from two arrays?

PHP: How to find the intersection (same values) from two arrays?

If you have two (or more) arrays with various values, how do you find the values from the 1st array that are also in the 2nd (and others) array? Use the intersect functions.

PHP has a nice collection of array functions - one of which is array_intersect. You can use it to solve this problem.

  1.        $array1 = ['apple','banana','grape','orange'];
  2. $array2 = ['cake', 'apple', 'toast', ];
  3.  
  4. $vals_in_both_arrays =  array_intersect($array1,$array2);

Which outputs an array with the single item in both arrays: ['apple'].


What if you need to compare the keys and values?

Then use array_intersect_assoc() which will compare both keys and values.

  1.  $array1 = ["aa" => "a",
  2.                     "bb" => "b",
  3.                     "cc" => "c",
  4.                     "dd" => "d"
  5.                 ];
  6.  
  7.         $array2 = [
  8.  
  9.             "dd" =>"d", // same as above
  10.             "foo" => "bar",
  11.             "bb" => "not_b",
  12.             "cc" => "c", //same as above
  13.             "aa" => "not_a",
  14.  
  15.  
  16.             ];
  17.  
  18.  
  19.         $same = (array_intersect_assoc($array1,$array2));
array:2 [
  "cc" => "c"
  "dd" => "d"
]

If you just want to compare the keys, then use array_intersect_keys().

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to find the intersection (same values) from two arrays?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to create random numbers in JS?

How to disable file hotlinking in Apache with .htaccess

How to check if a (blade) view file exists

What are the SPL data structures

How to find the index of a value in an array in JS?

How could you include a custom function for every single time PHP runs?

Why should you update APP_URL from from http://localhost?

How to find the intersection (same values) from two arrays?

How to Extract Query String (from a URL) Into an Associative Array in PHP

How to have a whitelist of IP addresses that can access files in .htaccess