Search code examples
phparraysarray-difference

array_dif not working as the output is empty


I created 2 arrays and want to check for the difference between both arrays (values). If I use my arrays with the function array_diff, the response is a empty Array, which is very wierd as I can't find the problem at all.

My setup:

// first array
$listing_products_sku = [
    '55995', '55996', '55999', '56000', '56005', '56006', '56007',
    '56008', '56021', '56022', '56023', '56024', '56029', '56030',
    '56031', '56032', '56036', '56037',
];

// second array:
$internal_products_sku = [
    '56015', '56016', '56014', '56018', '56019', '56020', '55994',
    '55995', '55996', '55997', '55998', '55999', '56000', '56001',
    '56002', '56003', '56005', '56004', '56006', '56007', '56008',
    '56009', '56010', '56011', '56012', '56013', '56017', '56021',
    '56022', '56023', '56024', '56025', '56026', '56027', '56028',
    '56029', '56030', '56031', '56032', '56033', '56034', '56035',
    '56036', '56037', '56038', '56039', '56040', '56041', '60434',
    '60435',
];

// used function:
$diff_result = array_diff($listing_products_sku, $internal_products_sku);
print_r($diff_result);

Output

Array ( ) 

Help needed

Is anybody able to explain why this happens and how I can make this working?


Solution

  • array_diff() returns array from first array containing values not exist in rest of the arrays (http://php.net/manual/en/function.array-diff.php). As your first array's element are already exist in second array ($internal_products_sku) this is why its returning empty array.

    So to find the difference all you have to do is take the $internal_products_sku array as first param then check

    $diff_result = array_diff($internal_products_sku, $listing_products_sku);
    print_r($diff_result);
    

    Now it will return an array with those value not exist in $listing_products_sku