Home > Backend Development > PHP Tutorial > PHP implementation to get the same/different elements in the array

PHP implementation to get the same/different elements in the array

王林
Release: 2023-04-08 08:48:01
forward
3043 people have browsed it

PHP implementation to get the same/different elements in the array

1. Get the same elements of the array

array_intersect() This function compares the key values ​​​​of two (or more) arrays, and Returns an intersection array containing all keys in the compared array (array1) and any other parameter arrays (array2 or array3, etc.).

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
  
$result=array_intersect($a1,$a2);
print_r($result);
  
//
Array ( [a] => red [b] => green [c] => blue )
Copy after login

(Free learning video tutorial sharing: php video tutorial)

array_intersect_assoc() function is used to compare the key names and keys of two (or more) arrays value, and returns the intersection. Different from the array_intersect() function, this function not only compares key values, but also compares key names. The keys of the elements in the returned array remain unchanged.

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"blue");
  
$result=array_intersect_assoc($a1,$a2);
print_r($result);
?>
//
Array ( [a] => red [b] => green [c] => blue )
Copy after login

2. Get different elements in the array

array_diff() function returns the difference array of 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.

<?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 )
Copy after login

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

<?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 )
Copy after login

Recommended related articles and tutorials: php tutorial

The above is the detailed content of PHP implementation to get the same/different elements in the array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
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