1. <?php
  2. /**
  3. * Removes duplicate strings from an array, handling edge cases.
  4. *
  5. * @param array $stringArray The input array of strings.
  6. * @return array The array with duplicates removed, preserving original order.
  7. */
  8. function removeDuplicateStrings(array $stringArray): array
  9. {
  10. if (empty($stringArray)) {
  11. return []; // Handle empty array case
  12. }
  13. $uniqueStrings = [];
  14. $seen = []; // Use an associative array for efficient lookup
  15. foreach ($stringArray as $string) {
  16. if (!in_array($string, $seen)) {
  17. $uniqueStrings[] = $string;
  18. $seen[] = $string;
  19. }
  20. }
  21. return $uniqueStrings;
  22. }
  23. //Example usage and testing
  24. if (PHP_SAPI === 'cli') {
  25. // Test cases
  26. $testCases = [
  27. ['apple', 'banana', 'apple', 'orange', 'banana'],
  28. [''],
  29. ['a', 'a', 'a'],
  30. [],
  31. ['apple'],
  32. ['apple', 'Apple', 'apple'], // Case sensitivity test
  33. ['apple', 'banana', 'orange', 'grape', 'apple', 'banana']
  34. ];
  35. foreach ($testCases as $testCase) {
  36. $result = removeDuplicateStrings($testCase);
  37. print_r($result . PHP_EOL);
  38. }
  39. }
  40. ?>

Add your comment