Home >Backend Development >PHP Problem >How to remove duplicate elements from array in php

How to remove duplicate elements from array in php

藏色散人
藏色散人Original
2022-12-26 10:14:074171browse

php method to remove duplicate elements from an array: 1. Create a php sample file; 2. Use the "array_unique" function to remove duplicate values ​​in the array; 3. Through "array_diff_assoc" and "array_diff()" The function compares the values ​​of two arrays and returns the difference.

How to remove duplicate elements from array in php

The operating environment of this tutorial: windows10 system, PHP version 8.1, DELL G3 computer

php How to remove duplicate elements from an array ?

php removes duplicate elements from the array

Interview computer questions

$a = [1, 2, 14, 2, 1]

Removes duplicate elements from the array, leaving 14 elements

Solution: If you want to get 14, you must first find 1 and 2, and then use the difference set method to get 14

Solution:

$b = array_unique($a);
$c = array_diff_assoc($a, $b);
$d = array_diff($a, $c);
var_dump($d);

Related introduction:

  • array_unique — Remove duplicate values ​​from an array

Description

array_unique(array $array, int $flags = SORT_STRING): array

array_unique() accepts array as input and returns a new array without duplicate values.

Note that the key name remains unchanged. If there are multiple equal elements when flags is specified, the key and value of the first equal element will be retained.

Note: Two units are considered the same if and only if (string) $elem1 === (string) $elem2. For example, when string expressions are the same, the first element is used.

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

This function compares the key names and key values ​​​​of two (or more) arrays, and returns a difference array, which includes all the arrays being compared (array1) in, but not in any other parameter array (array2 or array3, etc.).

Syntax

array_diff_assoc(array1,array2,array3...);
  • array_diff() function is used to compare the values ​​of two (or more) arrays and return the difference.

This function compares the values ​​​​of two (or more) arrays (value in key=>value) and returns a difference array, which includes all A value that is in the array being compared (array1), but not in any of the other argument arrays (array2 or array3, etc.).

Grammar

array_diff(array1,array2,array3...);

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to remove duplicate elements from array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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