<?php
/**
* Deduplicates an array of strings, returning a new array with unique values.
* Outputs error messages if input is invalid.
*
* @param array $stringArray The array of strings to deduplicate.
* @return array|string A new array with unique strings, or an error message.
*/
function deduplicateStrings(array $stringArray): array|string
{
if (!is_array($stringArray)) {
return "Error: Input must be an array.";
}
if (empty($stringArray)) {
return []; // Return empty array if input is empty
}
$uniqueStrings = [];
$seen = []; // Use an associative array for faster lookup
foreach ($stringArray as $string) {
if (!is_string($string)) {
return "Error: Array must contain only strings.";
}
if (!in_array($string, $seen, true)) { // strict type checking
$uniqueStrings[] = $string;
$seen[] = $string;
}
}
return $uniqueStrings;
}
// Example usage (and error handling demonstrations)
$strings1 = ["apple", "banana", "apple", "orange", "banana"];
$result1 = deduplicateStrings($strings1);
echo "Result 1: " . print_r($result1, true) . "\n";
$strings2 = []; // Empty array
$result2 = deduplicateStrings($strings2);
echo "Result 2: " . $result2 . "\n";
$strings3 = ["apple", 123, "banana"]; // Array with non-string
$result3 = deduplicateStrings($strings3);
echo "Result 3: " . $result3 . "\n";
$strings4 = "not an array"; // Not an array
$result4 = deduplicateStrings($strings4);
echo "Result 4: " . $result4 . "\n";
$strings5 = ["apple", "Apple"]; // Case sensitive
$result5 = deduplicateStrings($strings5);
echo "Result 5: " . print_r($result5, true) . "\n";
?>
Add your comment