How to Compare 2 Arrays in PHP

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

Comparing arrays is a common task in PHP programming, especially when dealing with data sorting, searching, or processing. In PHP, the comparison of two arrays can be performed in various ways depending on what aspects of the arrays you’re interested in comparing.

In this tutorial, we are going to explore different methods to compare two arrays in PHP. We’ll discuss straightforward comparisons as well as how to handle more complex scenarios.

Simple Comparison with == and ===

PHP offers two basic operators for array comparison:

  • == (Equal): This operator checks if two arrays have the same key/value pairs. The order of the elements is not considered.
  • === (Identical): This operator checks if two arrays have the same key/value pairs in the same order and of the same types.

Here’s a simple example comparing two arrays:


$array1 = array('a' => 'apple', 'b' => 'banana');
$array2 = array('b' => 'banana', 'a' => 'apple');
$array3 = array('a' => 'apple', 'b' => 'banana');

// Using == operator
var_dump($array1 == $array2); // bool(true)

// Using === operator
var_dump($array1 === $array2); // bool(false)
var_dump($array1 === $array3); // bool(true)

As the example demonstrates, the == operator returns true because the arrays have the same key/value pairs, ignoring the order, whereas, the === operator returns false for `$array1` and `$array2` because the order is different. When comparing `$array1` and `$array3`, both operators return true since the order is the same in addition to the key/value pairs.

Comparing Array Values with array_diff and array_intersect

The `array_diff` function returns an array containing all the entries from one array that are not present in one or more other arrays. Conversely, the `array_intersect` function returns an array with all the elements that are present in all the arrays being compared.


$array1 = array('apple', 'banana', 'cherry');
$array2 = array('banana', 'blueberry', 'cherry');

// Elements in $array1 not in $array2
$diff = array_diff($array1, $array2);
print_r($diff); // Outputs: Array
                        // (
                        //    [0] => apple
                        // )

// Elements present in both $array1 and $array2
$intersect = array_intersect($array1, $array2);
print_r($intersect); // Outputs: Array
                           // (
                           //     [1] => banana
                           //     [2] => cherry
                           // )

Note that both `array_diff` and `array_intersect` only compare the values of the arrays, not the keys. If the arrays have string keys, you should consider using `array_diff_assoc` or `array_diff_key` which include key comparison as well.

Advanced Comparisons Using User-Defined Functions

Sometimes the comparison criteria are more complex and cannot be handled by the standard PHP functions. In such cases, you may need to define your own comparison function. You can use the `usort`, `uksort`, and `uasort` functions along with a user-defined callback to compare arrays based on custom rules.


function myComparison($a, $b){
    if($a == $b){
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$array1 = array('apple', 'banana', 'cherry');
$sortedArray = $array1;
usort($sortedArray, 'myComparison');
print_r($sortedArray); // The $sortedArray is now sorted according to the myComparison function

This is a flexible approach when you want to control every aspect of the comparison, but be mindful that user-defined sort functions can affect performance due to overhead in calling the callback multiple times when sorting large arrays.

Multi-Dimensional Array Comparison

Multi-dimensional arrays require specialized comparison techniques. Neither the `array_diff` family of functions nor the simple equality operators can handle multi-dimensional arrays effectively.

For instance, if you want to compare whether two associative arrays contain the same sets of information, you might use a recursive approach or a combination of serialization and comparison:


$array1 = array(array('id' => 1, 'name' => 'John'), array('id' => 2, 'name' => 'Jane'));
$array2 = array(array('id' => 2, 'name' => 'Jane'), array('id' => 1, 'name' => 'John'));

$serializedArray1 = array_map('serialize', $array1);
$serializedArray2 = array_map('serialize', $array2);

$diff = array_diff($serializedArray1, $serializedArray2);
$intersect = array_intersect($serializedArray1, $serializedArray2);

print_r($diff); // Outputs: Array () - no differences
print_r($intersect); // Outputs the intersected elements

While serialization can work, it’s important to remember that it makes the code hard to read and can be inefficient.

Conclusion

Comparing arrays in PHP can be simple or complex depending on the structure and content of the arrays. Choosing the right approach is critical, whether it’s a simple key/value comparison or a bespoke comparison of multi-dimensional arrays with custom business logic. Being well-versed in PHP’s array functions and understanding when to use them is key to effective array comparison and manipulation in PHP.

With the wealth of functions and techniques available in PHP, developers have a robust toolbox for array comparison tasks. Whether leveraging built-in functions for standard comparisons or delving into user-defined functions for granular control, mastering array comparison is an essential skill for PHP developers.