Transform a csv file to associative array in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

 Transform a csv file to associative array in PHP

There are a lot of  examples on how to take a CSV file and put it in an array, but the main problem about them is that the header and the rest of the content from the csv are placed on separate keys, both on the same level. You don’t want that every time. Sometimes you want to have the header as a key and the rest of the content placed as value for that key. Let’s see a detailed example of what I am talking about:

Imagine the next csv file:

We want to obtain as the first key “itemcode” and as values “54215”, “48915” and “76915”. The same for the rest of the csv header items.

Now, if you call this function:

you will have the desired output:

It’s that simple.

 

Request an article ←