Home > Backend Development > PHP Problem > How to remove identical elements from two arrays in php

How to remove identical elements from two arrays in php

青灯夜游
Release: 2023-03-10 11:06:02
Original
1893 people have browsed it

PHP method to remove the same elements in two arrays: first nest two foreach loops to traverse the two arrays; then use the if statement in the loop body to find the same elements in the two arrays; finally use The unset() function can remove the same elements from the two arrays.

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 deletes the same in two arrays Elements of

<?php
	$a = [18,19,20,21,22];
	$b = [18,19,1];
	
	foreach ($a as $key=>$v1) {
		foreach($b as $key2=>$v2){
			if($v1==$v2){
			unset($a[$key]);//删除$a数组同值元素
			unset($b[$key2]);//删除$b数组同值元素
			}
		}
	}
	var_dump($a);	
	var_dump($b);
?>
Copy after login

Output:

How to remove identical elements from two arrays in php

## Related introduction:

unset() function

unset() function is used to destroy the given variable. The syntax is as follows:

void unset ( mixed $var [, mixed $... ] )
Copy after login

Parameter description:

  • $var: variable to be destroyed.

PHP foreach loop

PHP foreach loop structure is a commonly used method when traversing arrays. foreach can only be applied to arrays and objects. If you try Applications to variables of other data types or uninitialized variables will issue an error message.


foreach has the following two syntax formats:

//格式1
foreach (array_expression as $value){
    statement
}
//格式2
foreach (array_expression as $key => $value){
    statement
}
Copy after login
When the first format traverses the array_expression array, each loop assigns the value of the array to $value; the second traversal not only assigns the array value Assign to $value and assign the key name to $key.

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