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.
Array unique and flip in 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).
<?php $array = ['apple', 'banana', 'apple', 'orange']; $uniqueArray = array_unique($array); print_r($uniqueArray); ?>
<?php $array = ['a' => 'red', 'b' => 'green', 'c' => 'red']; $flippedArray = array_flip($array); print_r($flippedArray); ?>
<?php $array = []; $uniqueArray = array_unique($array); print_r($uniqueArray); ?>
<?php $array = ['onlyone']; $flippedArray = array_flip($array); print_r($flippedArray); ?>
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 // 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); ?>
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.
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.