Jump to content

More efficient method to find differences in arrays


NotionCommotion

Recommended Posts

I have two associated arrays which only contain unique integers.  I need to find the integers that are in $arr2 but not in $arry1 (i.e. [2,5,18]).  The arrays are not huge (max ~100 elements) and I am sure it doesn't matter, however, my OCD prevents me from wondering whether array_diff_key() might be more efficient than array_diff().  Or maybe a different approach?  Anyone know?  Thanks

$arr1=[3,6,9,12,15];
$arr2=[2,3,5,6,9,12,15,18];
Link to comment
Share on other sites

array_diff() will sort both arrays and diff them with the most efficient algorithm possible. The sorting would be the slowest part, however (a) it might actually be linear for pre-sorted arrays, but more importantly (b) it'll still be faster than anything you can write using PHP.

 

array_diff_key() compares keys. You don't want that.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.