Home >Backend Development >PHP Problem >How to get unique values ​​in two arrays in php

How to get unique values ​​in two arrays in php

青灯夜游
青灯夜游Original
2021-10-19 18:07:253141browse

php method to obtain unique values ​​in two arrays: 1. Use the array_diff() function, the syntax "array_diff(array 1, array 2)"; 2. Use the array_diff_assoc() function, the syntax "array_diff_assoc( Array1,Array2)".

How to get unique values ​​in two arrays in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, get 2 arrays without duplication The value of , that is, comparing two arrays and finding the different elements in the two arrays, that is, the difference set.

Let’s take a look at how to compare two arrays in php, just the difference set.

Method 1. Use the array_diff() function--compare the key values ​​of the array

array_diff($arr1,$arr2...) The function only compares the key values ​​of the array and returns a difference array. The elements in the difference array exist in the compared array $arr1, but do not exist in other parameter arrays $arr2 ...middle.

Example:

<?php
$arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow");

$result=array_diff($arr1,$arr2);
var_dump($result);
?>

How to get unique values ​​in two arrays in php

Method 2: Use the array_diff_assoc() function--compare the keys of the array Name and key value

array_diff_assoc($arr1,$arr2...)The function will compare the key name and key value of the array, and also return a difference array. Set elements will be obtained from the compared array $arr1 like array_diff().

Example:

<?php
$arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow");

$result=array_diff_assoc($arr1,$arr2);
var_dump($result);
?>

How to get unique values ​​in two arrays in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to get unique values ​​in two arrays in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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