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

Force trailing slash (redirect if no trailing slash exists) in .htaccess

What is the difference between var, let and const in Javascript?

How to group a SQL statement in brackets/parenthesis

What are macros in Laravel?

How to replace values in a string, in JS

How to get table column names from a database table in Eloquent?

What is the max size, by default, of GET variables?

What is the null coalescing operator in PHP7?

How to get a route to directly show a view?

A list of operators on Eloquent's where() method