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

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

王林
王林forward
2020-01-17 17:33:342980browse

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 )

(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 )

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 )

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 )

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!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete