Using PHP’s array_map to format your arrays without loops

So let’s face it, loops are a bit boring. So how can we mix it up? Let’s assume we have a case where we have a CSV file that we want to quickly parse. The CSV’s first row contains the headers for each column of the CSV. How can we setup a new array with each key of being the name of the header field and the corresponding values assigned to them without using loops? I’ll show you.

First thing we’ll want to understand is that PHP offers an alternative way to iterate through an array with the array_map function. For this example we’ll take a CSV of the U.S. state names and abbreviations. From this file we’ll want to output the data organized into an array where each field header name relates to the correct field value.

First let’s get a CSV. I used this file here.

Next we’ll want to write some code to parse out our file and extract the files header for later use.

The above snippet of code reads our file and returns each line as a new row in our array. After we’ve parsed the file, we next extract the first row out of our array using array_shift.

Now that we have the file parsing out of the way. Let’s start by using our array_map function. What we’re looking to do is the following.

  1. Iterate through array
  2. Pass the header to our anonymous function.
  3. Parse each CSV line and header into an array.
  4. Combine the 2 new arrays, header and line item, so that the header array becomes our keys, and the line item the actual values.
  5. Return the newly formatted line item.

You can see now that we’re able to apply a simple callback to each item of the array. If we were to print out the data of our states, you’ll see the following output.

See how simple that was? The code is now much simpler. Using this approach I believe also helps explain the intent behind your code more, making it easier for future developers to read your code base.