May 06 2008

Today’s Tip: php’s array_merge() doesn’t work well with an empty array

I spent several hours last night trying to figure out why my code wasn’t working. I had an array of tags that I wanted to add to my database. But, I only wanted to add the tags if they hadn’t already been added. The API that I was using only had a method to return me an array of the tags that were already on the database. So, I decided to get that array and then merge the two arrays, take out the duplicates with array_unique() and then find the difference (array_diff) between those unique tags and my new tags. The different tags would need to be added to the database.

What I didn’t know was that an empty database, producing an empty array would not work with array_merge(). Instead of just duplicating my new tag array (which is what I thought it would do), it gave a warning and didn’t return anything. So, my tags were never being added to the database.

I spent several hours tracking down that bug (mostly because it was in a SOAP call which ran very slowly for each test). Hopefully, this will help someone else not make the same mistake!

Happy Programming!

Cindy :)

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

WordPress Themes