Home » PHP/MySQL, Programming Techniques » Compare two arrays in PHP using array_diff | Check whether arrays are equal.


You want to compare two arrays in PHP. Basically what you need is to make sure that both the arrays contain the same set of values may or may not be in the same order. You can use the built-in PHP function, array_diff to compute the difference of arrays. But this function just checks whether all the values of array1 is in array2 and if not returns the values which are not present in array2.

Look at the code below.

$a = array("red", "green", "blue", "green");
$b = array("red", "green", "blue", "orange");
print_r(array_diff($b, $a));

This code returns a blank array because it could find all the elements in $a present in $b, though both arrays are different.

So, just depending on a single array_diff function will not give you the intended result. Instead, use it like this,

$a = array("red", "green", "blue", "green");
$b = array("red", "green", "blue", "orange");
if(!count(array_diff($a, $b)) && !count(array_diff($b, $a))) {
    // Arrays are equal
} else {
   // Array values are different

Hope this helps. Please let me know if you have any questions.


  1. $stringA = “this is php programming language”;
    $stringB = “this is complete programming script in which java php and all other minor languages include”;

    echo “string 1—->”.$stringA.”";
    echo “string 2—->”.$stringB.”";
    // changing string to arrays
    $array1 = explode(‘ ‘, $stringA);
    $array2 = explode(‘ ‘, $stringB);

    // getting same element from two strings
    $c = array_intersect($array1, $array2);
    // changing array to the string
    $d=implode(‘ ‘,$c);
    echo “string same elements—> “.$d.”";

    // getting difrent element from two arrays
    $result = array_diff($array2, $array1);
    // changing array to the string
    $zem= implode(‘ ‘,$result);

    if (!empty($zem)) {
    echo “string diffrence—> “.$zem.”";

    else {
    echo “string diffrence—>both strings are same “;

    similar_text($stringA, $d , $p);
    echo ” similarity between the stirng is “.$p.”% “;

  2. Chetan Patel says:

    Really umer singhera your information is help full thanks for the sharing dear next time you have any good tips then tale me.

  3. Aldor says:

    Agreed, except there is a little mistake:
    The first code will return Array( [3] => orange ), but

    print_r(array_diff($a, $b));

    will return empty array.

Leave a Reply

Page optimized by WP Minify WordPress Plugin