Home PHP Oh, how I love array_combine
Oh, how I love array_combine PDF Print E-mail
User Rating: / 0
PoorBest 
Written by Nate Lyman   
Monday, 08 February 2010 08:15

Let me just start by saying that it is late, but I am up late working on parsing a huge text file. 120,000,000 rows huge.  Anyway, let me enlighten you on the awesomeness of array_combine().

Imagine you have some tab delimited file that looks like this:

Show/Hidden php code

Imagine you want to parse this file row by row and load the data of each row into an associative array.  There is an overly complicated way you can do it, as seen below:

Show/Hidden php code

Enter array_combine(). You simply pass it in an array of keys, and the array of values, it returns an associative array. See the same function below using array_combine().

Show/Hidden php code

Obviously this doesn't save you a lot of lines of codes, but it saves you a minute or two.  The point is that you should use PHP's native function instead of writing your own, for readability, as well as performance.  For small arrays you wont see a performance gain, but for a larger array it will run about 30% faster.  Multiply the savings by the number of rows and it can end up being substantial.  This post is to aimed to help a developer that is new to PHP.  There are a lot of other uses for array_combine but I'll let you figure those out.

 

Add comment


Security code
Refresh

@natelyman

natelyman: #Bears RT @michaelombardi Darren Sharper just had his knee scoped and is on crutches so he had to cancel two visits.
natelyman: AMEN! RT @sam_trapkin: I'm just gonna put it out there that i think mayonnaise is digusting. You slimy freaks
natelyman: @joelfeder Thanks Buddy.
natelyman: Won second place out of 81 teams at an innovation competition at work. Hopefully I'll have a link to share soon when it goes live.
natelyman: Still waiting for Kanye to highjack an acceptance speech #AcademyAwards #Oscars
natelyman: @joelfeder the new Sonata is really nice. Kate's dad just got one.