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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.