Home > Article > Backend Development > php compare two arrays and remove duplicate values
The way PHP compares two arrays and deletes duplicate values is to use the array_diff function and take the two arrays that need to be compared as parameters, such as [array_diff(array1,array2,array3);].
The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.
If we want to compare two arrays and delete duplicate values in the two arrays, the easiest way is to use the array_diff function.
There may be many friends who are not familiar with the array_diff function. Let’s briefly introduce this function.
array_diff() function is used to compare the values of two (or more) arrays and return the difference.
This function compares the values of two (or more) arrays (key=>value in value), and returns a difference array, which includes all the arrays being compared (array1 ), but not in any other parameter array (array2 or array3, etc.).
Grammar:
array_diff(array1,array2,array3...);
Code example:
<!DOCTYPE html> <html> <body> <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"black","g"=>"purple"); $a3=array("a"=>"red","b"=>"black","h"=>"yellow"); $result=array_diff($a1,$a2,$a3); print_r($result); ?> </body> </html>
Running results:
Array ( [b] => green [c] => blue )
Related video sharing: php video tutorial
The above is the detailed content of php compare two arrays and remove duplicate values. For more information, please follow other related articles on the PHP Chinese website!