Get Unique Elements from Two Arrays in PHP

1. Basic Method (Preserves Types)

This is the simplest approach but maintains type differences. The number 12 and string “12” will be treated as distinct values.

Result: [5, 12, “18”, “12”] (keeps both 12 and “12”)

2. Type-Unified Method (Converts all to strings)

Converts all values to strings first, which ensures “12” and 12 become the same value. Useful when type differences don’t matter.

Result: [“5”, “12”, “18”] (all values as strings)

3. Numeric Method (Converts all to numbers)

Converts all values to integers, which is useful when you’re working with numeric data and want to ignore string/integer type differences.

Result: [5, 12, 18] (all values as integers)

4. Using array_diff with array_merge

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.

Note: This is one of the fastest methods for large arrays but reindexes the array.

5. Using the + Operator (Union)

The union operator (+) merges arrays but only works properly for associative arrays with unique keys. Not recommended for indexed arrays like in our example.

Warning: For numeric arrays, this method doesn’t work as expected for merging values.

6. Custom Function with array_reduce

This method provides complete control over the comparison process. The true parameter in in_array() ensures strict type comparison.

Advantage: You can customize the comparison logic as needed.

7. Using array_flip Twice

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.

Performance: This is very fast for large arrays but converts values to strings during the flip operation.

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)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.