In algorithms and data structures, array intersection and union are used to find elements that appear simultaneously and at least once respectively. PHP provides array_intersect() and array_union() functions to implement these operations, which can be used in practical applications, such as finding common friends between two users.
Theoretical basis
In algorithms and data structures, array intersection and union are two basic operations.
PHP code implementation
PHP has built-in array_intersect()
and array_union()
functions to calculate arrays Intersection and union:
$array1 = [1, 2, 3, 4, 5]; $array2 = [3, 4, 5, 6, 7]; // 交集 $intersection = array_intersect($array1, $array2); // 并集 $union = array_union($array1, $array2); print_r($intersection); // 结果:[3, 4, 5] print_r($union); // 结果:[1, 2, 3, 4, 5, 6, 7]
Practical case: Finding common friends of two users
Suppose we have a website where each user has a "friend" list. We want to find mutual friends between two users.
$user1Friends = [23, 45, 67, 89]; $user2Friends = [34, 45, 56, 89]; // 计算共同朋友 $commonFriends = array_intersect($user1Friends, $user2Friends); print_r($commonFriends); // 结果:[45, 89]
The above is the detailed content of Theoretical basis of PHP array intersection and union in algorithms and data structures. For more information, please follow other related articles on the PHP Chinese website!