PHP array_intersect() Tutorial 🎯

beginner
15 min

PHP array_intersect() Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into the PHP function array_intersect(). This powerful function helps you find common elements in two or more arrays. Let's get started!

What is array_intersect()? πŸ“

array_intersect() compares two or more arrays and returns a new array containing only the common elements. In other words, it helps you find the intersection of two or more sets.

Syntax πŸ’‘

Here's the syntax for array_intersect():

php
array array_intersect( array $array1, array $array2 [, array ...$arrays ] )
  • array1: The first array to compare.
  • array2: The second array to compare. If more than two arrays are given, they are compared one by one.

Example 1: Basic Usage βœ…

Let's see array_intersect() in action with a simple example:

php
// Create arrays $array1 = array("apple", "banana", "cherry", "orange"); $array2 = array("banana", "cherry", "grape", "orange"); // Use array_intersect() $common_elements = array_intersect($array1, $array2); // Print result print_r($common_elements);

Output:

Array ( [0] => banana [1] => cherry [2] => orange )

Example 2: Multiple Arrays βœ…

You can also use array_intersect() with more than two arrays to find the common elements among all of them:

php
// Create arrays $array1 = array("apple", "banana", "cherry", "orange"); $array2 = array("banana", "cherry", "grape", "orange"); $array3 = array("grape", "lemon", "orange", "pear"); // Use array_intersect() $common_elements = array_intersect($array1, $array2, $array3); // Print result print_r($common_elements);

Output:

Array ( [0] => orange )

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the PHP function `array_intersect()` do?

That's it for today! Stay tuned for more PHP tutorials on CodeYourCraft. Remember, practice makes perfect, so keep coding! πŸš€