Code Logo

Array Difference

Published at24 Jul 2026
PHP Data Structures Medium 0 views
Like0

Write a PHP function that returns all elements from the first array that do not appear in the second array. The result should contain only unique values (no duplicates). Order does not matter.

Use array_diff() which computes the difference of arrays. This function returns the values from the first array that are not present in any of the subsequent arrays. PHP's array_diff() compares values using (string) casting for comparison.

Medium difficulty because it requires understanding of array comparison semantics, handling of duplicate values, and knowledge of the built-in array_diff() behavior.

Array difference is a fundamental set operation in PHP. The array_diff() function computes values from the first array not present in subsequent arrays. Understanding array_diff() behavior with type comparison and duplicate values is important for correct usage.

The combination of array_unique() ensures no duplicates in the result. array_values() reindexes the result sequentially. This problem demonstrates how multiple PHP array functions compose to produce the desired output format.

The array_diff() function compares array values using the comparison (string) \$a == \$b after casting. For strict type comparison, array_diff() uses string casting which means 1 and '1' are considered equal. For identity comparison (===), a manual implementation using array_filter() with a closure is needed.

Example Input & Output

Example 1
Input
[], [1,2]
Output
[]
Example 2
Input
[1,2], []
Output
[1,2]
Example 3
Input
[1,2,2,1],[2]
Output
[1]
Example 4
Input
[5,5,5],[5]
Output
[]
Example 5
Input
[1,2,3],[2,3,4]
Output
[1]

Algorithm Flow

Recommendation Algorithm Flow for Array Difference
Recommendation Algorithm Flow for Array Difference

Solution Approach

Use array_diff($a, $b) which returns all elements from $a not present in $b. The comparison is done on string representations of the values. For unique results, combine with array_unique() if the first array has duplicates.

For a manual implementation without array_diff(), build a lookup map from the second array using array_flip() or a loop. Then iterate through the first array, checking if each element exists in the lookup map. If not, add it to the result.

Edge cases include empty arrays, arrays with duplicate values, and associative arrays (array_diff works with keys).

Best Answers

php - Approach 1
<?php
function arrayDiff($a, $b) {
    return array_values(array_unique(array_diff($a, $b)));
}