PHP中如何删除重复字符串及其原重复项?
Hey there! Let's tackle this problem where we need to remove all instances of duplicate strings (including their original occurrences) in PHP. I'll walk you through a couple of straightforward, practical approaches.
array_count_values() + array_filter() This is my go-to method for this task—it's concise and leverages PHP's built-in functions to keep things clean. Here's how it works:
- First, we count how many times each string appears in the array using
array_count_values(). - Then, we filter out any string that has a count greater than 1 with
array_filter().
$originalArray = ["apple", "banana", "apple", "orange", "banana", "grape"]; // Step 1: Count occurrences of each element $counts = array_count_values($originalArray); // Step 2: Filter out elements that appear more than once $uniqueOnlyArray = array_filter($originalArray, function($value) use ($counts) { return $counts[$value] === 1; }); // Optional: Reindex the array (array_filter preserves original keys) $uniqueOnlyArray = array_values($uniqueOnlyArray); print_r($uniqueOnlyArray); // Output: Array ( [0] => orange [1] => grape )
If you want to understand the underlying logic better (or need more control), you can manually count occurrences first, then build your result array. This is great for learning or customizing the behavior:
$originalArray = ["apple", "banana", "apple", "orange", "banana", "grape"]; $counts = []; $result = []; // First pass: Count how many times each item appears foreach ($originalArray as $item) { $counts[$item] = isset($counts[$item]) ? $counts[$item] + 1 : 1; } // Second pass: Collect only items that show up exactly once foreach ($originalArray as $item) { if ($counts[$item] === 1) { $result[] = $item; } } print_r($result); // Same output: Array ( [0] => orange [1] => grape )
If you're working with associative arrays and want to preserve the original keys, just skip the array_values() step in Approach 1. For Approach 2, adjust the second loop to keep keys:
foreach ($originalArray as $key => $item) { if ($counts[$item] === 1) { $result[$key] = $item; } }
By default, PHP treats "Apple" and "apple" as distinct strings. If you need case-insensitive removal, modify the counting step to normalize the case:
$originalArray = ["Apple", "banana", "apple", "orange", "Banana", "grape"]; // Normalize to lowercase for counting $lowercaseCounts = array_count_values(array_map('strtolower', $originalArray)); $uniqueOnlyArray = array_filter($originalArray, function($value) use ($lowercaseCounts) { return $lowercaseCounts[strtolower($value)] === 1; }); $uniqueOnlyArray = array_values($uniqueOnlyArray); print_r($uniqueOnlyArray); // Output: Array ( [0] => orange [1] => grape )
内容的提问来源于stack exchange,提问作者sertegh

