To find the intersection of two sets in PHP, you can use the array_intersect function.
In this example,
$set1
and $set2
.array_intersect
function to find the intersection of $set1
and $set2
.<?php
$set1 = [1, 2, 3, 4, 5];
$set2 = [4, 5, 6, 7, 8];
$intersection = array_intersect($set1, $set2);
print_r($intersection);
?>
Array ( [3] => 4 [4] => 5 )
In this example,
$set1
and $set2
.$set1
using a foreach
loop and check if each element is present in $set2
.$intersection
array.<?php
$set1 = [1, 2, 3, 4, 5];
$set2 = [4, 5, 6, 7, 8];
$intersection = [];
foreach ($set1 as $item) {
if (in_array($item, $set2)) {
$intersection[] = $item;
}
}
print_r($intersection);
?>
Array ( [0] => 4 [1] => 5 )
In this tutorial, we learned How to find Intersection of Two Sets in PHP language with well detailed examples.