Core answer: PHP array intersection and union functions can respectively find the intersection and union of two arrays, and are widely used in data processing. Usage: Intersection (array_intersect): Returns the common elements in two arrays. Union (array_merge): Returns all elements in two arrays, including duplicates. Practical case: Compare user input preferences and verify legality. Merge two shopping lists to create a combined list of all unique items. Find duplicates in two arrays to facilitate data analysis.
PHP Examples of practical application of array intersection and union in data processing
Array intersection and union are processed in PHP Two commonly used functions for arrays. This article will outline their usage and demonstrate their application in real-world data processing.
1. Overview
2. Usage
// 交集 $intersection = array_intersect($array1, $array2); // 并集 $union = array_merge($array1, $array2);
3. Practical case
Case 1: Compare user input
Suppose a website form asks users to provide a list of interests and hobbies. You can use array intersection to compare the user input list to the list of hobbies available in the database. The hobbies in the intersection represent the legitimate hobbies selected by the user.
// 用户输入的爱好 $inputHobbies = ['游泳', '篮球', '阅读']; // 数据库中的爱好 $dbHobbies = ['游泳', '篮球', '网球', '烹饪']; // 计算交集 $commonHobbies = array_intersect($inputHobbies, $dbHobbies); // 验证输入 if (empty($commonHobbies)) { echo '您选择的爱好无效'; } else { echo '您选择的爱好:' . implode(', ', $commonHobbies); }
Case 2: Merging Shopping Lists
Suppose two friends create their own shopping lists. You can use array union to create a combined list that contains all unique items.
// 朋友 A 的清单 $listA = ['苹果', '香蕉', '牛奶']; // 朋友 B 的清单 $listB = ['面包', '鸡蛋', '牛奶']; // 计算并集 $mergedList = array_merge($listA, $listB); // 输出合并后的清单 echo '合并后的购物清单:' . implode(', ', $mergedList);
Case 3: Finding Duplicates in Arrays
You can use array union to find duplicate elements in two arrays. Duplicates will appear in the union array.
// 数组 1 $array1 = [1, 2, 3, 4, 5]; // 数组 2 $array2 = [2, 4, 6, 8]; // 计算并集 $union = array_merge($array1, $array2); // 查找重复项 $duplicates = array_unique($union); echo '重复项:' . implode(', ', $duplicates);
The above is the detailed content of Practical application examples of PHP array intersection and union in data processing. For more information, please follow other related articles on the PHP Chinese website!