How to compare arrays in php and obtain different elements

青灯夜游
Release: 2023-03-12 11:22:01
Original
3351 people have browsed it

Method: 1. Use array_diff() to compare based on the array key value, the syntax is "array_diff(array 1, array 2)"; 2. Use array_diff_assoc() to compare based on the array "key/value pair", Syntax "array_diff_assoc(array1,array2)".

How to compare arrays in php and obtain different elements

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

Method 1: Use 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 will return a difference array. The elements in the set array exist in the compared array $arr1, but do not exist in other parameter arrays $arr2....

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow");
var_dump($arr1);
var_dump($arr2);
$result=array_diff($arr1,$arr2);
echo "两个数组中,不同的元素为:";
var_dump($result);
?>
Copy after login

Output result:

How to compare arrays in php and obtain different elements

Method 2: Use array_diff_assoc() function --Compare the key names and key values ​​of the array

array_diff_assoc($arr1,$arr2...)The function will compare the key names and key values ​​of the array and return the same A difference array, the difference elements will be obtained from the compared array $arr1 just like array_diff().

<?php
header("Content-type:text/html;charset=utf-8");
$arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow");
var_dump($arr1);
var_dump($arr2);

$result=array_diff_assoc($arr1,$arr2);
echo "两个数组中,不同的元素为:";
var_dump($result);
?>
Copy after login

Output result:

How to compare arrays in php and obtain different elements

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to compare arrays in php and obtain different elements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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