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
- How to increment variable value by 1 in php
- How to add new item to array in PHP
- Convert comma-separated string into array in PHP
- How to add elements to an empty array in PHP?
- How to displaying ckeditor save HTML data from SQL database
- How to add php8.2 in ubuntu
- Page view counter in PHP
- How to get image tmp_name in PHP
- Required parameter $originalDate follows optional parameter $format
- How to set php executable path php.validate.executablePath in vscode
- Type hinting in PHP
- User-defined functions in php
- Service container sample code in PHP mvc framework
- How to check If an element exists in Array in php
- How to check file is an image in php
- Array to string conversion error in PHP
- How to display data in ckeditor?
- Convert string to sha512 in PHP
- Shorthand for isset() in php
- How to remove duplicate values from Array in PHP
- How to get date with day, month, year, weekdays from string "2021/08/12" in php
- If statement with multiple conditions in php
- Delay code execution in PHP
- You are trying to access an array as object
- PHP number format indian currency