PHP array_diff() - Complete Guide with Examples

Mahesh Mahesh Waghmare
5 min read

The array_diff() function compares arrays and returns values present in the first array but not in the others. It’s essential for finding differences, filtering arrays, and data comparison tasks.

This comprehensive guide covers everything about array_diff(), from basic usage to advanced patterns.

Introduction to array_diff()

array_diff() compares arrays and returns values from the first array that don’t exist in any of the other arrays.

Key Characteristics:

  • Compares values only (not keys)
  • Uses loose comparison (==)
  • Preserves keys from first array
  • Returns new array

Common Use Cases:

  • Find missing values
  • Compare datasets
  • Filter arrays
  • Data synchronization
  • Remove duplicates

Syntax and Parameters

Function Signature

array_diff(array $array, array ...$arrays): array

Parameters

$array (required):

  • First array to compare
  • Values from this array are returned if not in others

...$arrays (optional):

  • One or more arrays to compare against
  • Values in these arrays are excluded from result

Return Value

Returns array containing values from first array that don’t exist in other arrays, preserving keys.

Advertisement

Basic Usage Examples

Simple Two-Array Comparison

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];

$diff = array_diff($array1, $array2);
// Result: [0 => 1, 1 => 2]
// Values 1 and 2 are in $array1 but not in $array2

String Arrays

$array1 = ['apple', 'banana', 'orange'];
$array2 = ['banana', 'grape'];

$diff = array_diff($array1, $array2);
// Result: [0 => 'apple', 2 => 'orange']

Associative Arrays

$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['a' => 1, 'b' => 2];

$diff = array_diff($array1, $array2);
// Result: ['c' => 3]
// Keys are preserved from first array

Multiple Array Comparison

Compare Against Multiple Arrays

$array1 = [1, 2, 3, 4, 5];
$array2 = [2, 3];
$array3 = [4];

$diff = array_diff($array1, $array2, $array3);
// Result: [0 => 1, 4 => 5]
// Values not in any of the other arrays

Real-World Example

$allUsers = [1, 2, 3, 4, 5];
$activeUsers = [2, 3, 4];
$premiumUsers = [3, 4, 5];

// Find inactive, non-premium users
$inactive = array_diff($allUsers, $activeUsers, $premiumUsers);
// Result: [0 => 1]

Key Preservation

Keys Are Preserved

$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$array2 = [2, 4];

$diff = array_diff($array1, $array2);
// Result: ['a' => 1, 'c' => 3]
// Keys 'a' and 'c' are preserved

Reindex Result

$array1 = [1, 2, 3, 4];
$array2 = [2, 3];

$diff = array_diff($array1, $array2);
// Result: [0 => 1, 3 => 4] - keys preserved

// Reindex
$diff = array_values(array_diff($array1, $array2));
// Result: [0 => 1, 1 => 4] - keys reset

Strict vs Loose Comparison

Loose Comparison (Default)

array_diff() uses loose comparison (==):

$array1 = [1, '1', true, 0];
$array2 = ['1'];

$diff = array_diff($array1, $array2);
// Result: [] - all values match due to loose comparison

Strict Comparison Alternative

Use array_diff_assoc() or custom function:

function array_diff_strict($array1, $array2) {
    $result = [];
    foreach ($array1 as $key => $value) {
        if (!in_array($value, $array2, true)) {
            $result[$key] = $value;
        }
    }
    return $result;
}

$diff = array_diff_strict([1, '1'], ['1']);
// Result: [0 => 1] - only integer 1 differs
Advertisement

Common Patterns

Find Missing Values

$required = ['name', 'email', 'phone'];
$provided = ['name', 'email'];

$missing = array_diff($required, $provided);
// Result: [2 => 'phone']

Find Extra Values

$allowed = ['name', 'email', 'phone'];
$provided = ['name', 'email', 'age', 'city'];

$extra = array_diff($provided, $allowed);
// Result: [2 => 'age', 3 => 'city']

Synchronize Arrays

$source = [1, 2, 3, 4, 5];
$target = [2, 3, 6, 7];

// Values to add to target
$toAdd = array_diff($source, $target);
// Result: [0 => 1, 3 => 4, 4 => 5]

// Values to remove from target
$toRemove = array_diff($target, $source);
// Result: [2 => 6, 3 => 7]

Real-World Examples

Form Validation

function validateFormFields($data, $required) {
    $missing = array_diff($required, array_keys($data));
    
    if (!empty($missing)) {
        return ['error' => 'Missing fields: ' . implode(', ', $missing)];
    }
    
    return ['success' => true];
}

$required = ['name', 'email', 'phone'];
$data = ['name' => 'John', 'email' => 'john@example.com'];
$result = validateFormFields($data, $required);

User Permissions

$allPermissions = ['read', 'write', 'delete', 'admin'];
$userPermissions = ['read', 'write'];

$missingPermissions = array_diff($allPermissions, $userPermissions);
// Result: [2 => 'delete', 3 => 'admin']

Data Comparison

$oldData = [1, 2, 3, 4, 5];
$newData = [2, 3, 4, 6, 7];

$removed = array_diff($oldData, $newData);
// Result: [0 => 1, 4 => 5]

$added = array_diff($newData, $oldData);
// Result: [3 => 6, 4 => 7]

Best Practices

  1. Understand loose comparison - values like 1, ‘1’, true may match
  2. Reindex if needed - use array_values() for sequential keys
  3. Check empty result - empty(array_diff()) to verify no differences
  4. Combine with other functions - use with array_intersect(), array_merge()

Conclusion

array_diff() is essential for:

  • Finding array differences
  • Data comparison
  • Filtering arrays
  • Synchronization tasks

Key Takeaways:

  • Compares values only (not keys)
  • Uses loose comparison
  • Preserves keys from first array
  • Works with multiple arrays
  • Returns new array

Mastering array_diff() enhances your PHP array manipulation capabilities.

Advertisement
Mahesh Waghmare

Written by Mahesh Waghmare

I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.

Follow on Twitter

Read Next