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 pick what array_intersect function to use in PHP?

Is multiple inheritance supported in PHP?

How to redirect your website to a new domain/location in .htaccess

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

How to set up an alias to map one directory to another destination

What are the predefined variables in PHP?

How to show a specific view file for certain error codes?

What is Agile software development?

How to check if a string contains a certain substring?

How to reverse htmlentities() / What is the opposite of htmlentities()?