How to Compare Two Arrays in PHP?

Given two arrays i.e. Array1, and Array2, the task is to compare both arrays in PHP. The comparison checks for equality finds differences, or determines common elements. PHP offers several functions and methods to compare arrays effectively.

Below are the approaches to compare two arrays in PHP:

Table of Content

  • Using array_diff() Function
  • Using array_diff_assoc() Function

Using array_diff() Function

The array_diff() function compares the values of two (or more) arrays and returns the values from the first array that are not present in any of the other arrays.

Example: This example shows the use of the above-mentioned approach.

PHP
<?php

$arr1 = [10, 20, 30, 40];
$arr2 = [10, 30, 40, 20];

$diff = array_diff($arr1, $arr2);

if ($diff) {
    echo "Both Arrays are not same";
} else {
    echo "Both Arrays are same";
}

?>

Output
Both Arrays are same

Using array_diff_assoc() Function

The array_diff_assoc() function compares both the values and the keys of two (or more) arrays and returns the differences.

Example: This example shows the use of the above-mentioned approach.

PHP
<?php

$arr1 = [
    "a" => "HTML", 
    "b" => "CSS", 
    "c" => "JavaScript"
];

$arr2 = [
    "b" => "CSS", 
    "c" => "JavaScript", 
    "a" => "HTML"
];

$diff = array_diff_assoc($arr1, $arr2);

if ($diff) {
    echo "Both Arrays are not same";
} else {
    echo "Both Arrays are same";
}

?>

Output
Both Arrays are same

Contact Us