1. <?php
  2. /**
  3. * Deduplicates an array of strings, returning a new array with unique values.
  4. * Outputs error messages if input is invalid.
  5. *
  6. * @param array $stringArray The array of strings to deduplicate.
  7. * @return array|string A new array with unique strings, or an error message.
  8. */
  9. function deduplicateStrings(array $stringArray): array|string
  10. {
  11. if (!is_array($stringArray)) {
  12. return "Error: Input must be an array.";
  13. }
  14. if (empty($stringArray)) {
  15. return []; // Return empty array if input is empty
  16. }
  17. $uniqueStrings = [];
  18. $seen = []; // Use an associative array for faster lookup
  19. foreach ($stringArray as $string) {
  20. if (!is_string($string)) {
  21. return "Error: Array must contain only strings.";
  22. }
  23. if (!in_array($string, $seen, true)) { // strict type checking
  24. $uniqueStrings[] = $string;
  25. $seen[] = $string;
  26. }
  27. }
  28. return $uniqueStrings;
  29. }
  30. // Example usage (and error handling demonstrations)
  31. $strings1 = ["apple", "banana", "apple", "orange", "banana"];
  32. $result1 = deduplicateStrings($strings1);
  33. echo "Result 1: " . print_r($result1, true) . "\n";
  34. $strings2 = []; // Empty array
  35. $result2 = deduplicateStrings($strings2);
  36. echo "Result 2: " . $result2 . "\n";
  37. $strings3 = ["apple", 123, "banana"]; // Array with non-string
  38. $result3 = deduplicateStrings($strings3);
  39. echo "Result 3: " . $result3 . "\n";
  40. $strings4 = "not an array"; // Not an array
  41. $result4 = deduplicateStrings($strings4);
  42. echo "Result 4: " . $result4 . "\n";
  43. $strings5 = ["apple", "Apple"]; // Case sensitive
  44. $result5 = deduplicateStrings($strings5);
  45. echo "Result 5: " . print_r($result5, true) . "\n";
  46. ?>

Add your comment