0
0
PHPprogramming~5 mins

Array unique and flip in PHP

Choose your learning style9 modes available
Introduction

We use array unique and flip to remove duplicate values and swap keys with values in an array. This helps organize data and find unique items easily.

When you want to remove repeated items from a list of names.
When you need to switch keys and values to look up data quickly.
When cleaning up user input to keep only unique entries.
When preparing data for quick search by values instead of keys.
Syntax
PHP
<?php
// Remove duplicates from an array
$uniqueArray = array_unique($array);

// Flip keys and values in an array
$flippedArray = array_flip($array);
?>

array_unique() keeps the first occurrence and removes later duplicates.

array_flip() swaps keys and values; values must be unique and valid keys (strings or integers).

Examples
Removes duplicate 'apple', keeps first one.
PHP
<?php
$array = ['apple', 'banana', 'apple', 'orange'];
$uniqueArray = array_unique($array);
print_r($uniqueArray);
?>
Flips keys and values; last duplicate value 'red' overwrites previous key.
PHP
<?php
$array = ['a' => 'red', 'b' => 'green', 'c' => 'red'];
$flippedArray = array_flip($array);
print_r($flippedArray);
?>
Empty array stays empty after unique.
PHP
<?php
$array = [];
$uniqueArray = array_unique($array);
print_r($uniqueArray);
?>
Single element array flips key 0 and value 'onlyone'.
PHP
<?php
$array = ['onlyone'];
$flippedArray = array_flip($array);
print_r($flippedArray);
?>
Sample Program

This program shows how to remove duplicates from an array and then flip keys and values. It prints the array before and after each step.

PHP
<?php
// Original array with duplicates
$fruits = ['apple', 'banana', 'apple', 'orange', 'banana'];

// Print original array
echo "Original array:\n";
print_r($fruits);

// Remove duplicates
$uniqueFruits = array_unique($fruits);
echo "\nArray after removing duplicates:\n";
print_r($uniqueFruits);

// Flip keys and values
$flippedFruits = array_flip($uniqueFruits);
echo "\nArray after flipping keys and values:\n";
print_r($flippedFruits);
?>
OutputSuccess
Important Notes

Time complexity: array_unique() and array_flip() both run in O(n) time, where n is the number of elements.

Space complexity: Both functions create new arrays, so space is O(n).

Common mistake: Using array_flip() on arrays with duplicate values causes keys to be overwritten silently.

Use array_unique() when you want to keep only one copy of each value. Use array_flip() when you want to quickly find keys by their values.

Summary

array_unique() removes duplicate values, keeping the first occurrence.

array_flip() swaps keys and values, but values must be unique and valid keys.

These functions help organize and search data efficiently in arrays.