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

How Can I Remove Duplicate Values from an Array in PHP?

Mary-Kate Olsen
Release: 2024-12-27 03:17:09
Original
146 people have browsed it

How Can I Remove Duplicate Values from an Array in PHP?

Removing Duplicate Values from Arrays in PHP

Eliminating duplicate values from arrays is a common task in PHP. Here are two effective methods to achieve this:

1. Using array_unique()

The array_unique() function returns a new array with duplicate values removed. It preserves key-value pairs, retains the first equal element, and does not work on multidimensional arrays.

$array = [1, 2, 2, 3];
$array = array_unique($array); // Array becomes (1, 2, 3)
Copy after login

2. Using array_values() with array_unique()

If you need the values re-indexed after removing duplicates, combine array_unique() with array_values():

$array = [1, 2, 2, 3];
$array = array_values(array_unique($array)); // Array becomes (1, 2, 3) re-indexed
Copy after login

Remember, array_unique() returns a new array, so make sure to assign it to a new variable or update the original variable reference.

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