Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get difference between two or more arrays in PHP?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 500
    Comment on it

    Hello friends,

    Today we learn how to find out the difference between two or more arrays. Difference between two or more arrays can be based upon key and value of arrays. PHP provides following functions to fulfill the same:

    1. array_diff() Function:
    array_diff() function works on the basis of the value of two or more arrays. In other words, comparison of two or more arrays is done on the basis of the values and once compared it returns their differences.

    Syntax:

    array_diff(array1,array2,array3...);

    array1: array1 is the array from which others array are compared. It is required parameter.

    array2: array2 is the array against which comparison performed. It is also a required parameter.

    array3,....: array3.... are other array again which comparison performed. It is a optional parameter.

    Example:

    <?php
    $arr1=array(3,4,5);
    $arr2=array(1,2,3);
    $result=array_diff($arr1,$arr2);
    print_r($result);
    ?>

    Output of above example is as follows:

    Array ( [1] => 4 [2] => 5 ) 

    2. array_diff_key() Function:

    array_diff_key() function works on the basis of the key of two or more arrays. In other words, comparison of two or more arrays is done on the basis of the keys and once compared it returns their differences.

    Syntax:

    array_diff_key(array1,array2,array3...);

    array1: array1 is the array from which others array are compared. It is required parameter.

    array2: array2 is the array against which comparison performed. It is also a required parameter.

    array3,....: array3.... are other array again which comparison performed. It is a optional parameter.

    Example:

    <?php
    $arr1=array("key1"=>"val1","key2"=>"val2","key3"=>"val3");
    $arr2=array("key1"=>"val5","key4"=>"val6","key5"=>"val3");
    $result=array_diff_key($arr1,$arr2);
    print_r($result);
    ?>

    Output of above example is as follows:

    Array ( [key2] => val2 [key3] => val3 )

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: