How to remove identical elements from two arrays in php

青灯夜游
Release: 2023-03-11 10:48:01
Original
2576 people have browsed it

In PHP, you can use the array_diff() function to remove the same elements from two arrays. The syntax format is "array_diff(array1,array2);"; this function is used to compare the values ​​of two arrays and can return A difference array containing all values ​​in array1 but not in array2.

How to remove identical elements from two arrays in php

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

php removes two identical arrays Element

can use the array_diff() function, the code example is as follows:

<?php
header("Content-type:text/html;charset=utf-8");
$a=array(1,2,3);
$b=array(2,3,4);
//得到存在于$a但不存在于$b中的元素组成的数组
$c1=array_diff($a,$b);
//得到存在于$b但不存在于$a中的元素组成的数组
$c2=array_diff($b,$a);
//去除相同元素后的两个数组
echo &#39;去除相同元素后的两个数组:&#39;.&#39;<br>&#39;;
var_dump($c1);
var_dump($c2);
?>
Copy after login

Output:

去除相同元素后的两个数组:
array (size=1)
  0 => int 1
array (size=1)
  2 => int 4
Copy after login

Explanation:

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

Syntax

array_diff(array1,array2,array3...);
Copy after login
Parameters Description
array1 Required. The first array to compare with other arrays.
array2 Required. The array to compare to the first array.
array3,... Optional. Additional array to compare with the first array.

array_diff() compares the values ​​of two (or more) arrays (value in key=>value) and returns a difference array; difference set The array includes all values ​​that are in the array being compared (array1) but not in any of the other parameter arrays (array2 or array3, etc.).

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove identical elements from two arrays in php. 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