PHP - Check if two arrays are equal
In PHP, verifying that two arrays are identical requires more than a simple equality check. When you compare two structures containing collections of data, the goal is usually to ensure they match in three specific dimensions: size, key association (index), and value content. The language provides built-in functions designed for this exact scenario, but understanding their nuances prevents subtle bugs in your application logic.
The most straightforward approach for associative or indexed arrays is using the array_equal() function if you are running PHP 8.2 or later, or relying on the classic == operator with caveats. However, the industry standard for strict comparisonâwhere keys and values must align exactlyâis provided by the === operator when applied to specific array types, or more robustly via the array_is_equal() function introduced in PHP 8.2.
For legacy codebases or environments running older PHP versions, developers often rely on array_compare(). This function returns an integer indicating equality (0) or inequality (1), but it treats arrays as values rather than objects, meaning it compares them element by element without considering object identity. If you need to handle multidimensional arrays where the structure itself matters, array_is_equal() is generally safer because it respects the order and keys strictly, unlike a loose comparison which might reorder numeric indices or perform type juggling that masks logical errors.
Consider a scenario where you are validating user input against stored session data. If $data1 represents the expected state and $data2 represents the submitted form values, using === is insufficient because PHP arrays are objects in memory. The expression $_POST['atlOriginal'] !== $oldAtlPosition checks scalar inequality, but if you are comparing two entire arrays, a loose equality check (==) might return true even if one array has a different key order or contains an empty string instead of null, depending on the context.
The source material highlights a common pitfall involving strict inequality operators (!==). The code snippet provided attempts to trigger an action if any of four specific variables differ:
if (($_POST['atlOriginal'] !== $oldAtlPosition)
or ($_POST['atl'] !== $aext)
or ($_POST['sidesOriginal'] !== $oldSidePosition)
or ($_POST['sidesOriginal'] !== $sideext)) {
echo "enter";
}
While this logic works for scalar comparisons, it fails if the developer intended to compare entire arrays stored in these variables. If $oldAtlPosition and $_POST['atlOriginal'] are arrays, using !== will only check object identity. Two arrays with identical content but different memory addresses (which is almost always the case) will return true for inequality, which is correct behavior for strict comparison, but the logic becomes fragile if the arrays are converted to strings or if type coercion occurs unexpectedly in older PHP versions.
If you need to verify that two complex arrays are truly duplicates, including nested structures, array_is_equal() is the modern solution. It returns true only if both arrays have the same keys and values, preserving the order of elements for indexed arrays. For example:
$arrayA = ['name' => 'John', 'age' => 30];
$arrayB = ['name' => 'John', 'age' => 30];
var_dump(array_is_equal($arrayA, $arrayB)); // bool(true)
$arrayC = ['name' => 'John', 'age' => 30];
// Reordering keys for associative arrays matters in strict comparison context
$arrayD = ['age' => 30, 'name' => 'John'];
var_dump(array_is_equal($arrayA, $arrayD)); // bool(false) - Keys differ
When implementing this check in a framework like Laravel, you might find yourself comparing request attributes or model casts. While Laravel does not expose array_is_equal() directly as a helper method by default, you can utilize the array_is_equal function globally if your PHP version supports it, or fall back to iterating through keys for older versions. In many cases, using the built-in diff_assoc() or array_udiff() combined with an empty result check offers a compatible alternative for strict equality verification across different PHP versions.
One critical trade-off involves performance versus strictness. Using a simple loop to compare elements manually is slower but gives you control over how null values or type conversions are handled. However, unless you have specific requirements to ignore key order or treat 0 and false as equivalent, the built-in functions handle these edge cases more predictably than custom loops.
Finally, ensure that your PHP version meets the requirements for the function you choose. If you are working with a legacy system on PHP 7.x, array_is_equal() is unavailable, forcing you to use array_compare() or manual iteration. Always verify the exact behavior of array comparisons in your specific environment, as changes in PHP versions regarding type juggling and key ordering can significantly impact the result of equality checks.