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

How to Remove Duplicate Values from a PHP Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 20:46:14672browse

How to Remove Duplicate Values from a PHP Array?

Eliminating Duplicate Array Values in PHP

Ever encountered duplicate elements polluting your PHP arrays? To purify their contents and maintain data integrity, you'll need a technique for removing these redundant values.

Solution: Array_unique

For one-dimensional arrays, the array_unique() function comes to the rescue. As per the PHP documentation, this function:

  • Generates a new array devoid of duplicate values.
  • Maintains the original keys.
  • Skips multi-dimensional arrays.

Example:

<?php
$array = array(1, 2, 2, 3);
$uniqueArray = array_unique($array); // Result: (1, 2, 3)
?>

Reindexing for Clean Slates

If you require re-indexed array elements, consider using the array_values() function in conjunction with array_unique().

Example:

<?php
$array = array(1, 2, 2, 3);
$uniqueArray = array_values(array_unique($array)); // Result: (0 => 1, 1 => 2, 2 => 3)
?>

The above is the detailed content of How to 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