How to remove duplicate values from array using PHP? - GeeksforGeeks (2024)

Last Updated : 29 Jul, 2024

Summarize

Comments

Improve

In this article, we will discuss removing duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.

Syntax:

array array_unique($array, $sort_flags);

Note: The keys of the array are preserved i.e. the keys of the not removed elements of the input array will be the same in the output array.

Parameters:

This function accepts two parameters that are discussed below:

  • $array: This parameter is mandatory to be supplied and it specifies the input array from which we want to remove duplicates.
  • $sort_flags: It is an optional parameter. This parameter may be used to modify the sorting behavior using these values:
    • SORT_REGULAR: This is the default value of the parameter $sort_flags. This value tells the function to compare items normally (don’t change types).
    • SORT_NUMERIC: This value tells the function to compare items numerically.
    • SORT_STRING: This value tells the function to compare items as strings.
    • SORT_LOCALE_STRING: This value tells the function to compare items as strings, based on the current locale.

Return Value:

The array_unique() function returns the filtered array after removing all duplicates from the array.

Using array_unique() function

The array_unique() function in PHP removes duplicate values from an array by comparing the values and removing subsequent occurrences. It returns a new array with only unique values while preserving the original order of elements. This function is simple and efficient for deduplicating arrays in PHP applications.

Example 1: PHP program to remove duplicate values from the array.

PHP
<?php // Input Array$a = array( "red", "green", "red", "blue");// Array after removing duplicatesprint_r(array_unique($a));?>

Output:

Array
(
[0] => red
[1] => green
[3] => blue
)

Example 2: PHP program to remove duplicate elements from an associative array.

PHP
<?php // Input array$arr = array( "a" => "MH", "b" => "JK", "c" => "JK", "d" => "OR");// Array after removing duplicatesprint_r(array_unique($arr));?>

Output:

Array
(
[a] => MH
[b] => JK
[d] => OR
)

Example 3: This is another way of removing the duplicates from the array using the PHP in_array() method.

PHP
<?php // This is the array in which values// will be stored after removing// the duplicates$finalArray = array();// Input array$arr = array( "a" => "MH", "b" => "JK", "c" => "JK", "d" => "OR");foreach ($arr as $key => $value){ // If the value is already not stored // in the final array if (!in_array($value, $finalArray)) $finalArray[$key] = $value;} // End foreachprint_r($finalArray);?>

Output:

Array
(
[a] => MH
[b] => JK
[d] => OR
)

Using array_filter()

To remove duplicate values from an array using `array_filter()`, apply a callback function that checks each element’s index against its first occurrence. Return true only for the first occurrence to filter out duplicates.

Example: This example shows the use of the above-mentioned approach.

PHP
<?php$array = [1, 2, 2, 3, 4, 4, 5];$uniqueArray = array_filter($array, function($value, $key) use ($array) { return array_search($value, $array) === $key;}, ARRAY_FILTER_USE_BOTH);print_r(array_values($uniqueArray));?>

Output

Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5)

Using Iteration and Comparison

To remove duplicate values from an array in PHP without using `array_unique()`, iterate through the array, check each value’s existence in a separate array (`$uniqueArray`), and append it if not already present.

Example: This example shows the use of the above-mentioned approach.

PHP
<?phpfunction removeDuplicates($array) { $uniqueArray = []; foreach ($array as $value) { // Check if the value is already in $uniqueArray if (!in_array($value, $uniqueArray)) { $uniqueArray[] = $value; } } return $uniqueArray;}// Example array with duplicate values$array = [1, 2, 2, 3, 4, 4, 5];// Remove duplicates$uniqueArray = removeDuplicates($array);// Print the unique arrayprint_r($uniqueArray);?>

Output

Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5)

Using array_flip() and array_values() Functions:

The array_flip() function in PHP exchanges keys with their associated values in an array, effectively removing duplicate values. `array_values()` is then used to reset the array indices, providing a cleaned-up array without duplicate values while maintaining the original order.

Example

PHP
<?php$array = array("apple", "banana", "cherry", "apple", "banana");$uniqueArray = array_values(array_flip($array));print_r($uniqueArray);?>

Output

Array( [0] => 3 [1] => 4 [2] => 2)

Using array_count_values()

The `array_count_values()` function counts all the values of an array and returns an associative array where keys are the original values and values are their counts. To remove duplicates, filter keys with a count of 1, and then use `array_keys()` to extract unique values.

Example:

PHP
<?php$array = [1, 2, 2, 3, 4, 4, 5];// Count values$valueCounts = array_count_values($array);// Filter to keep only values that appear once$uniqueValues = array_keys(array_filter($valueCounts, function($count) { return $count === 1;}));print_r($uniqueValues);?>

Output

Array( [0] => 1 [1] => 3 [2] => 5)


D

deepakresearch222

How to remove duplicate values from array using PHP? - GeeksforGeeks (1)

Improve

Next Article

How to Remove Duplicate Elements from an Array using Lodash ?

Please Login to comment...

How to remove duplicate values from array using PHP? - GeeksforGeeks (2024)
Top Articles
Display Images In React
Can You Pay to Have Your Credit Fixed?
Dainty Rascal Io
Celebrity Extra
Nwi Police Blotter
Tv Guide Bay Area No Cable
10 Popular Hair Growth Products Made With Dermatologist-Approved Ingredients to Shop at Amazon
Videos De Mexicanas Calientes
Paketshops | PAKET.net
Ohiohealth Esource Employee Login
Large storage units
Https //Advanceautoparts.4Myrebate.com
Immediate Action Pathfinder
Superhot Unblocked Games
Craigslist Pets Longview Tx
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Mzinchaleft
Tygodnik Polityka - Polityka.pl
Effingham Bookings Florence Sc
Mahpeople Com Login
How to Watch the Fifty Shades Trilogy and Rom-Coms
EASYfelt Plafondeiland
Dwc Qme Database
Great Clips Grandview Station Marion Reviews
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Mtr-18W120S150-Ul
Haunted Mansion Showtimes Near Epic Theatres Of West Volusia
Rogue Lineage Uber Titles
Dei Ebill
Synergy Grand Rapids Public Schools
Is Henry Dicarlo Leaving Ktla
Alternatieven - Acteamo - WebCatalog
Deleted app while troubleshooting recent outage, can I get my devices back?
Xemu Vs Cxbx
Best Weapons For Psyker Darktide
KITCHENAID Tilt-Head Stand Mixer Set 4.8L (Blue) + Balmuda The Pot (White) 5KSM175PSEIC | 31.33% Off | Central Online
Sabrina Scharf Net Worth
Hireright Applicant Center Login
3 bis 4 Saison-Schlafsack - hier online kaufen bei Outwell
Wilson Tire And Auto Service Gambrills Photos
Memberweb Bw
Tommy Bahama Restaurant Bar & Store The Woodlands Menu
Lyons Hr Prism Login
Booknet.com Contract Marriage 2
Sacramentocraiglist
Bonecrusher Upgrade Rs3
Lebron James Name Soundalikes
Is Chanel West Coast Pregnant Due Date
Skyward Login Wylie Isd
Powah: Automating the Energizing Orb - EnigmaticaModpacks/Enigmatica6 GitHub Wiki
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Att Corporate Store Location
Latest Posts
Article information

Author: Errol Quitzon

Last Updated:

Views: 5919

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Errol Quitzon

Birthday: 1993-04-02

Address: 70604 Haley Lane, Port Weldonside, TN 99233-0942

Phone: +9665282866296

Job: Product Retail Agent

Hobby: Computer programming, Horseback riding, Hooping, Dance, Ice skating, Backpacking, Rafting

Introduction: My name is Errol Quitzon, I am a fair, cute, fancy, clean, attractive, sparkling, kind person who loves writing and wants to share my knowledge and understanding with you.