1. Basic Method (Preserves Types)
1 2 3 4 5 |
$array1 = [5, 12]; $array2 = ["18", "12"]; $merged = array_merge($array1, $array2); $unique = array_unique($merged); |
This is the simplest approach but maintains type differences. The number 12 and string “12” will be treated as distinct values.
2. Type-Unified Method (Converts all to strings)
1 |
$unique = array_unique(array_map('strval', array_merge($array1, $array2))); |
Converts all values to strings first, which ensures “12” and 12 become the same value. Useful when type differences don’t matter.
3. Numeric Method (Converts all to numbers)
1 |
$unique = array_unique(array_map('intval', array_merge($array1, $array2))); |
Converts all values to integers, which is useful when you’re working with numeric data and want to ignore string/integer type differences.
4. Using array_diff with array_merge
1 2 |
$merged = array_merge($array1, $array2); $unique = array_keys(array_flip($merged)); |
This clever technique uses array_flip() which automatically removes duplicate values since array keys must be unique. Then we extract the keys back to values.
5. Using the + Operator (Union)
1 |
$unique = $array1 + $array2; |
The union operator (+) merges arrays but only works properly for associative arrays with unique keys. Not recommended for indexed arrays like in our example.
6. Custom Function with array_reduce
1 2 3 4 5 6 7 |
$unique = array_reduce(array_merge($array1, $array2), function($carry, $item) { if (!in_array($item, $carry, true)) { $carry[] = $item; } return $carry; }, []); |
This method provides complete control over the comparison process. The true
parameter in in_array() ensures strict type comparison.
7. Using array_flip Twice
1 |
$unique = array_flip(array_flip(array_merge($array1, $array2))); |
Similar to method 4, this exploits the fact that array keys must be unique. Flipping twice removes duplicates while preserving the last occurrence of each value.
Recommendations
- For small arrays where type matters: Use Method 1 (basic array_unique)
- For numeric data: Use Method 3 (convert to int)
- For large arrays: Use Method 4 or 7 (array_flip techniques)
- When you need custom comparison logic: Use Method 6 (array_reduce)