Home  >  Article  >  Backend Development  >  How to find different elements in two arrays in php

How to find different elements in two arrays in php

青灯夜游
青灯夜游Original
2021-05-10 17:41:002112browse

Two methods: 1. Use the array_diff() function, the syntax is "array_diff(array 1, array 2)"; 2. Use the array_diff_assoc() function to compare the key names and key values ​​of the two arrays and return the difference. Set, syntax "array_diff_assoc(array1,array)".

How to find different elements in two arrays in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

Get two arrays Different elements (difference set) in

1. Use array_diff() function

array_diff() function returns the difference set of two arrays array. This array contains all keys that are in the array being compared, but are not in any of the other argument arrays.

In the returned array, the key names remain unchanged.

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);
print_r($result);
?>
//
Array ( [d] => yellow )

2. Use the array_diff_assoc() function

array_diff_assoc() function is used to compare the key names and key values ​​of two (or more) arrays and return difference set.

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"blue");

$result=array_diff_assoc($a1,$a2);
print_r($result);
//
Array ( [d] => yellow )

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to find different elements 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