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: Happy 103993/33102 Day!
natelyman: @chitownforte22 it smells like a turd covered in burnt hair!
natelyman: @mikvogel @rgiertz @chriswoods85 Vogel hit the nail on the head.
natelyman: My flight is booked for PHP Tek-X in Chicago May 18-22 Woohoo!