Jump to content

Comparing 2 arrays and pulling unique values out


SCook

Recommended Posts

Here is my question:  I am pulling a list of cities from a database.  The cities are coming from two different tables and I am putting them into arrays.  Now, I need to compare the two arrays and remove any duplicate cities and then end up with one array filled with unique values.

  I've tried a few things, but with little success.  I can just see the answer but not quite yet.  Any tips would be great.  Thanks.

Well, I found a solution before anynoen posted, though i appreciate it.  And these will probably work too.

 

What I did was use array_filter() This function itereates through an array and sends each value to a callback function.  So, I iterate through the second array and compare each value to every value in the first.  If it matches, I return false, which does NOT add that value to the new array calling array_filter.  When true, that value from the callback function is added. 

 

Then I simply array_merge the two arrays.  Too bad PHP doesn't have a built in array compare function, but these method work too, I guess.  Thanks.

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.