the difference of two arrays in PHP


Answers ( 1 )


    To find the difference of two arrays in PHP, you can use the array_diff() function. This function compares the values of two or more arrays and returns the differences. Here is how you can use it:

    PHP Example

    Suppose you have two arrays:

    $array1 = ["apple", "banana", "cherry"];
    $array2 = ["banana", "pear", "peach"];

    To find the elements in $array1 that are not in $array2, use array_diff() like this:

    $difference = array_diff($array1, $array2);

    This will output:

        [0] => apple
        [2] => cherry


    • array_diff($array1, $array2) compares $array1 against $array2.
    • It returns an array containing all the entries from $array1 that are not present in any of the other arrays.


    • The keys are preserved. In the output array, you will see that the keys are the same as in $array1.
    • If you want to compare keys as well as values, you might consider using array_diff_assoc().
    • To compare more than two arrays, you can add more arrays as arguments to array_diff().

    Alternative Function: array_diff_assoc()

    If you also need to consider the keys in the comparison, use array_diff_assoc(). This function behaves similarly to array_diff(), but it also checks the keys from the arrays.


    • Use array_diff() for comparing array values.
    • Use array_diff_assoc() for comparing both array values and keys.
    • These functions are suitable for indexed arrays and associative arrays alike.

Leave an answer