PHP Array Deduplication & Sorting Tool
Description
This PHP function takes an array, removes duplicate values while preserving original keys, and then sorts the array by value. It handles both numeric and string values.
Code Snippet
<?php
function deduplicateAndSortArray(array $arr): array {
// Remove duplicates while preserving keys
$uniqueArr = array_unique($arr, SORT_REGULAR);
// Sort the array by value
asort($uniqueArr);
return $uniqueArr;
}
// Example usage:
$myArray = ["banana" => 1, "apple" => 3, "orange" => 2, "banana" => 1, "grape" => 4, "apple" => 3];
$sortedArray = deduplicateAndSortArray($myArray);
print_r($sortedArray);
?>