<?php
/**
* Removes duplicate strings from an array, handling edge cases.
*
* @param array $stringArray The input array of strings.
* @return array The array with duplicates removed, preserving original order.
*/
function removeDuplicateStrings(array $stringArray): array
{
if (empty($stringArray)) {
return []; // Handle empty array case
}
$uniqueStrings = [];
$seen = []; // Use an associative array for efficient lookup
foreach ($stringArray as $string) {
if (!in_array($string, $seen)) {
$uniqueStrings[] = $string;
$seen[] = $string;
}
}
return $uniqueStrings;
}
//Example usage and testing
if (PHP_SAPI === 'cli') {
// Test cases
$testCases = [
['apple', 'banana', 'apple', 'orange', 'banana'],
[''],
['a', 'a', 'a'],
[],
['apple'],
['apple', 'Apple', 'apple'], // Case sensitivity test
['apple', 'banana', 'orange', 'grape', 'apple', 'banana']
];
foreach ($testCases as $testCase) {
$result = removeDuplicateStrings($testCase);
print_r($result . PHP_EOL);
}
}
?>
Add your comment