Home > Backend Development > PHP Problem > How to find the union of arrays in php

How to find the union of arrays in php

青灯夜游
Release: 2023-03-16 09:26:01
Original
3372 people have browsed it

Method to find the union of arrays: 1. Use array_merge() to merge multiple arrays into one array, the syntax is "array_merge(array1, array2...)"; 2. Use "array_values(array_unique) (Merge Arrays))" removes duplicate values ​​from the merged arrays and reorders them.

How to find the union of arrays in php

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

What is a union?

Given two sets A and B, the set formed by merging all their elements together is called the union of set A and set B.

What is array union?

Simply put, it is a set that combines two or more arrays to remove duplicates.

php method to find the union of arrays

1. Merge arrays

In PHP, the array_merge() function is used To merge multiple arrays into one

array_merge() function will merge the elements of multiple arrays, and the elements of the next array will be appended to the previous array, and finally return the merged array.

If the original array has the same string key name, then the value after the key name will overwrite the previous value; if the original array contains a numeric key name, then the subsequent value will not Overwrites the previous value and appends it instead.

<?php
header("Content-type:text/html;charset=utf-8");
$arr1 = [1,2,3,4,5];
$arr2 = [2,3,6,7,8,9];
var_dump($arr1);
var_dump($arr2);
$result = array_merge($arr1,$arr2);
var_dump($result);
?>
Copy after login

How to find the union of arrays in php

2. Remove duplicate values ​​and reorder

  • array_unique() function can Remove duplicate values ​​from an array

  • array_values() function can reorder

<?php
header("Content-type:text/html;charset=utf-8");
$arr1 = [1,2,3,4,5];
$arr2 = [2,3,6,7,8,9];
$result = array_merge($arr1,$arr2);
var_dump($result);
$res=array_values(array_unique($result));
var_dump($res);
?>
Copy after login

How to find the union of arrays in php

Recommended study:《PHP video tutorial

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