PHP array introductory tutorial: finding array difference set

WBOY
Release: 2016-07-25 08:57:56
Original
3472 people have browsed it
This article introduces the method of finding the difference set of PHP arrays. Friends in need can refer to it.

In php, find the difference of arrays.

You need to use the difference function of the array: array_diff(). PHP array function array_diff(), returns values ​​that appear in the first array but not in other input arrays. This function is the opposite of array_intersect(). array array_diff(array array1,array array2[,arrayN…])

Let’s look at a simple example:

<?php  
//求数组的差集
$fruit1 = array("Apple","Banana","Orange");  
$fruit2 = array("Pear","Apple","Grape");  
$fruit3 = array("Watermelon","Orange","Apple");  
$intersection = array_diff($fruit1, $fruit2, $fruit3);  
print_r($intersection);
//by bbs.it-home.org
// output  
// Array ( [1] => Banana )  
?>
Copy after login

Then we will introduce the method of taking the difference between two arrays in PHP.

Let’s look at the definition and usage of the array_diff() function.

Definition and usage The array_diff() function returns an array of differences between two arrays. This array contains all keys that are in the array being compared, but are not in any of the other parameter arrays. In the returned array, the key names remain unchanged.

Grammar array_diff(array1,array2,array3...

Parameter description array1 required. The first array to compare with other arrays. array2 required. The array to compare to the first array. array3 Optional. The array to compare to the first array.

Tips One or more arrays can be compared to the first array.

Notes Only values ​​are used for comparison.

Example:

<?php
    $str1=array(0=>"Cat",1=>"Dog",2=>"Horse");
    $str2=array(3=>"Horse",4=>"Dog",5=>"Fish");
    $result = array_diff($str1,$str2);
    dump($result);
    //求数组差集 by bbs.it-home.org
?>
Copy after login

Output: array 0=>string 'Cat'(length=3)



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!