← Back to Chapters

PHP Array_Values & Array_Unique

? PHP Array_Values & Array_Unique

? Quick Overview

PHP provides useful functions to manipulate array values. The array_values() and array_unique() functions are commonly used to work with arrays that may have duplicate values or non-sequential keys. These functions help you clean up and retrieve unique values from arrays.

⚡ Key Concepts

  • array_values() – Returns all the values from an array and reindexes the array numerically.
  • array_unique() – Removes duplicate values from an array and returns a new array with only unique values.

? Syntax & Theory

array_values() is useful when you need a clean indexed array, while array_unique() focuses on removing repeated values. Both functions return new arrays and do not modify the original array.

? Example 1: Using array_values()

? View Code Example
// Reindexing an associative array into a numeric array
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "cherry");
$values = array_values($array);
print_r($values);
?>

? Explanation

The array_values() function extracts only the values and resets the keys starting from index 0.

? Example 2: Using array_unique()

? View Code Example
// Removing duplicate values from an indexed array
<?php
$array = array("apple", "banana", "apple", "cherry", "banana");
$unique = array_unique($array);
print_r($unique);
?>

? Explanation

The duplicate values are removed while the original keys remain unchanged.

? Example 3: array_unique() with Associative Arrays

? View Code Example
// Removing duplicate values while preserving associative keys
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "apple", "d" => "cherry");
$unique = array_unique($array);
print_r($unique);
?>

? Explanation

Only duplicate values are removed, and the first occurrence of each value keeps its original key.

? Interactive Insight

array_values()

array_unique()

Try switching themes using the toggle above to see how code readability adapts to light and dark modes.

? Use Cases

  • Cleaning user-submitted data.
  • Removing repeated entries from datasets.
  • Reindexing arrays before JSON encoding.

✅ Tips & Best Practices

  • Use array_values() after array_unique() if you need sequential indexes.
  • Remember that array_unique() compares values only, not keys.
  • Combine array functions for efficient data cleanup.

? Try It Yourself

  • Create an associative array of countries and capitals and extract only capitals.
  • Remove duplicate colors from an array.
  • Test arrays with mixed numeric and string values.