1. <?php
  2. /**
  3. * Deduplicates an array of strings, handling potential errors gracefully.
  4. *
  5. * @param array $strings An array of strings to deduplicate.
  6. * @return array An array containing only unique strings, or an empty array on failure.
  7. */
  8. function deduplicateStrings(array $strings): array
  9. {
  10. try {
  11. // Use array_unique for deduplication. Handles different data types gracefully.
  12. $uniqueStrings = array_unique($strings);
  13. // Check if array_unique returned an error.
  14. if ($uniqueStrings === false) {
  15. // Handle the error gracefully. Log it, or return an empty array.
  16. error_log("Deduplication failed: array_unique returned false.");
  17. return [];
  18. }
  19. return $uniqueStrings;
  20. } catch (Exception $e) {
  21. // Catch any unexpected exceptions.
  22. error_log("An unexpected error occurred during deduplication: " . $e->getMessage());
  23. return [];
  24. }
  25. }
  26. // Example Usage (for testing)
  27. // $data = ["apple", "banana", "apple", "orange", "banana"];
  28. // $deduplicatedData = deduplicateStrings($data);
  29. // print_r($deduplicatedData);
  30. ?>

Add your comment