PHP Array Intersect

PHP Array Intersect

Last Updated on Feb 14, 2023

Introduction

If you want to find the items in your array that are present in the other arrays, array intersect is your friend.

Here we have 3 arrays:

$people = [
   'php'      => 'amir',
   'feedhive' => 'simon',
   'twitter'  => 'pratham',
   'docker'   => 'francesco',
   'web3'     => 'oliver',
   'saas'     => 'simon'
];
$peopleA = [
   'php'      => 'amir',
   'feedhive' => 'simon',
   'twitter'  => 'pratham',
   'php'      => 'amir',
];
$peopleB = [
   'twitter'  => 'pratham',
   'docker'   => 'francesco',
   'web3'     => 'oliver',
   'saas'     => 'simon',
   'php'      => 'amir updated',
];

Array Intersect

we want to find the items in people array that are present in peopleA and peopleB arrays.

There are 3 different array intersect functions and we should choose them based on what we want to compare.

array_intersect if we want to compare based on values

array_intersect_key if we want to compare based on keys

array_intersect_assoc if we want to compare based on keys and values

Let’s see what is the result of each on of them

$people = [
   'php'      => 'amir',
   'feedhive' => 'simon',
   'twitter'  => 'pratham',
   'docker'   => 'francesco',
   'web3'     => 'oliver',
   'saas'     => 'simon'
];
$peopleA = [
   'php'      => 'amir',
   'feedhive' => 'simon',
   'twitter'  => 'pratham',
   'php'      => 'amir',
];
$peopleB = [
   'twitter'  => 'pratham',
   'docker'   => 'francesco',
   'web3'     => 'oliver',
   'saas'     => 'simon',
   'php'      => 'amir updated',
];
array_intersect($people,$peopleA,$peopleB);
//Array
//(
//    [feedhive] => simon
//    [twitter] => pratham
//    [saas] => simon
//)

array_intersect_key($people,$peopleA,$peopleB);
//Array
//(
//    [php] => amir
//    [twitter] => pratham
//)

array_intersect_assoc($people,$peopleA,$peopleB);
//Array
//(
//    [twitter] => pratham
//)

Conclusion

Now you know about array intersect function in PHP.

I recommend you to open a PHP files and try to define multiple arrays. then try to find the values that intersect between the arrays.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • array intersect function in PHP
  • array intersect based on keys
  • array intersect based on values
  • array intersect based on keys and values

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses