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 manually write your own pagination in PHP

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

How to block access to certain referrers in Apache using .htaccess

How to set infinite execution time in a PHP script

How to set environmental variables in your .htaccess file

How to install jpegtran for Linux CentOS

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

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

Set PHP config Variables (like ini_set) with .htaccess

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess