• Post category:PHP

Best Examples to Learn PHP array-_intersect Function

PHP Array Intersect Function

In this article, we will see what is the use of the PHP array intersect() function with an example.

If you want to find the common elements between two or more arrays, we need to use PHP array_intersect() function. We can pass two or more arguments to this function. This function returns common values of given arrays. Let’s see some example code.

Ex: common values between Two arrays

<?php
$orange = array('red', 'yellow');
$green = array('yellow', 'blue');
// finding common values
$common = array_intersect($orange, $green);
print_r($common);
?>

Output:

Array intersect function

  1. See the above code, we have created two different arrays namely $orange and $green.
  2. In these arrays, we gave one common value. To find that common value, we need to use PHP array_intersect() function.
  3. Then we pass the $orange and $green array variables as arguments to that function.
  4. Here the common value is ‘yellow’, see the output “yellow” displayed successfully.

Ex: common values between Three arrays

<?php
$car = array('wheel', 'engine', 'brake', 'steering');
$bike = array('wheel', 'engine', 'brake');
$cycle = array('wheel', 'brake', 'chain');
// finding common values
$common = array_intersect($car, $bike, $cycle);
print_r($common);
?>

Output:

Array intersect function

 

  1. In the above code, we have created three different arrays namely car, bike and cycle. And all three arrays have wheel and brake values.
  2. To find the common values, we need to use array_intersect() functional and pass the arrayname as parameter as in the above code.

I hope you have understood a little about how to get command values of two or more arrays in PHP. If you have any doubts about this then please comment below.

Leave a Reply