How to remove duplicate items from an array in PHP
In PHP, you can remove duplicate items from an array using the array_unique() function which is a in-built function in PHP. You can also use array_values(array_flip($originalArray)); to remove the duplicate items from original array in PHP.
-
Remove duplicate items from array using array_unique function
You can use array_unique function to get the unique array items from array. You can use sort() method on $array or you can apply sort() method on $output to sort the array items in ascending order.
$array = [1, 2, 4, 4, 5]; $output = array_unique($array); print_r($output);
Output :
Array ( [0] => 2 [1] => 1 [3] => 4 [5] => 5 )
-
Remove duplicate items from an array using array_values with array_flip function
$originalArray = array(1, 2, 3, 4, 2, 5, 6, 1); $uniqueArray = array_values(array_flip($originalArray)); print_r($uniqueArray);
Output :
Array ( [0] => 7 [1] => 4 [2] => 2 [3] => 3 [4] => 5 [5] => 6 )
-
Remove duplicat items from array using in_array function in foreach loop
$array = [2, 1, 2, 3, 3, 4, 5, 5 ,7 , 1]; sort($array); $output = []; foreach($array as $arrItem){ if(!in_array($arrItem, $output)){ $output[] = $arrItem; } }
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 7 )
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Php
- Page view counter in PHP
- Convert an array to string in PHP
- How to displaying ckeditor save HTML data from SQL database
- Type hinting in PHP
- If statement with multiple conditions in php
- Class "finfo" not found
- Convert comma-separated string into array in PHP
- Convert string to sha512 in PHP
- How to get date with day, month, year, weekdays from string "2021/08/12" in php
- Required parameter $originalDate follows optional parameter $format
- How to check If an element exists in Array in php
- How to add php8.2 in ubuntu
- How to remove duplicate values from Array in PHP
- Get the first key of an array in php
- Show errors in php
- How to increment variable value by 1 in php
- How to check file is an image in php
- How to get image tmp_name in PHP
- Array to string conversion error in PHP
- Service container sample code in PHP mvc framework
- How to add elements to an empty array in PHP?
- PHP number format indian currency
- You are trying to access an array as object
- User-defined functions in php
- How to add new item to array in PHP