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
Release: 2024-12-17 04:39:24
Original
236 people have browsed it

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]
Copy after login

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]
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template