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!
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.
Here's the syntax for array_intersect():
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.Let's see array_intersect() in action with a simple example:
// 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
)
You can also use array_intersect() with more than two arrays to find the common elements among all of them:
// 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
)
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! π