← Back to Chapters

PHP Array Diff & Udiff Functions

? PHP Array Diff & Udiff Functions

? Quick Overview

PHP provides powerful array comparison functions that help identify differences between arrays. array_diff() compares values directly, while array_udiff() allows custom comparison logic using user-defined functions.

⚡ Key Concepts

  • Value-based comparison using array_diff()
  • Custom logic comparison using array_udiff()
  • Keys from the first array are preserved in results

? Syntax & Theory

  • array_diff(array1, array2, ...) compares values only
  • array_udiff(array1, array2, ..., callback) compares using a custom function
  • The callback must return 0, <0, or >0

? Example 1: Using array_diff()

? View Code Example
// Compare two arrays and return values unique to the first array

? Live Output / Explanation

The output contains apple and date because these values exist only in the first array.

? Example 2: Using array_udiff()

? View Code Example
// Custom comparison function using strcmp

? Live Output / Explanation

The custom comparison logic produces the same result as array_diff() but allows flexibility.

? Example 3: array_udiff() with Multiple Arrays

? View Code Example
// Compare multiple arrays using a custom comparison function

? Live Output / Explanation

Only apple is unique to the first array when compared against all others.

? Use Cases

  • Finding removed items between datasets
  • Validating user input against allowed values
  • Comparing lists from multiple sources

? Interactive Concept

Think of array_diff() as a simple filter and array_udiff() as a programmable filter where you define how comparison works.

✅ Tips & Best Practices

  • Use array_diff() for simple comparisons
  • Use array_udiff() for case-insensitive or custom logic
  • Apply array_values() if reindexing is needed

? Try It Yourself

  • Compare numeric arrays using array_diff()
  • Build a case-insensitive comparison using array_udiff()
  • Test arrays with mixed data types