Home >Backend Development >PHP Tutorial >How Can I Remove Duplicate Values from a PHP Array?

How Can I Remove Duplicate Values from a PHP Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 04:39:24320browse

How Can I Remove Duplicate Values from a PHP Array?

Removing Duplicate Values from Arrays in PHP

When dealing with arrays in PHP, it may be necessary to remove duplicate values to ensure data accuracy and efficiency.

Solution: array_unique()

For one-dimensional arrays, the native array_unique() function effectively removes duplicate values. It retains the key-value pair of the first instance of each unique element, preserving key order.

$array = [1, 2, 2, 3];
$array = array_unique($array); // Array is now [1, 2, 3]

Note: array_unique() is not suitable for multi-dimensional arrays.

Reindexing Values

If desired, you can use array_values() to reindex the array, starting from 0:

$array = array_unique($array);
$array = array_values($array); // Array is now [1, 2, 3] with keys [0, 1, 2]

The above is the detailed content of How Can I Remove Duplicate Values from a PHP Array?. 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