OneBite.Dev - Coding blog in a bite size

Check If Two Arrays Are Equal In PHP

Code snippet for how to Check If Two Arrays Are Equal In PHP with sample and detail explanation

Determining whether two arrays are identical is a frequent requirement in PHP development. This article presents a simple and direct method for assessing the equality of two arrays using PHP and also provides an explanation of how the utilized code works.

Code Snippet for Checking Array Equality in PHP

Here’s the sample code snippet that allows us to compare two arrays in PHP:

<?php
    // Define two arrays
    $array1 = array("Red", "Green", "Blue");
    $array2 = array("Blue", "Green", "Red");

    // Sort the arrays
    sort($array1);
    sort($array2);

    // Check if arrays are equal
    if ($array1 == $array2) 
    {
        echo "The arrays are equal.";
    } 
    else 
    {
        echo "The arrays are not equal.";
    }
?>

In this code, two arrays are defined with the same elements but in a different order. The code sorts the arrays and then uses the equal comparison operator to determine if they’re equal.

Code Explanation for Checking Array Equality in PHP

Now, let’s break down the code step by step to understand how it functions:

  1. Defining the Arrays: The initial step of the code snippet establishes two arrays - $array1 and $array2. Both arrays possess the exact same elements but are not in the same order.
    $array1 = array("Red", "Green", "Blue");
    $array2 = array("Blue", "Green", "Red");
  1. Sorting the Arrays: The code sorts the arrays using the sort() function, which takes the reference of the array as an argument and sorts the process in ascending order by default. This step is important, as the order of the elements may vary even though the arrays are identical.
    sort($array1);
    sort($array2);
  1. Comparing the Arrays: The equality comparison operator (==) is used to check if the now sorted arrays are equal. This operator checks if both arrays have the same key/value pairs. Since the arrays are sorted in ascending order, if they are identical it would mean they have the same elements in the same order.
    if ($array1 == $array2) 
    {
        echo "The arrays are equal.";
    } 
    else 
    {
        echo "The arrays are not equal.";
    }

In summary, this PHP code snippet is easy to implement and is an effective way to determine the equality of two arrays irrespective of their element order.

php