From the course: PHP Tips, Tricks, and Techniques

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Export associative arrays from a CSV

Export associative arrays from a CSV

From the course: PHP Tips, Tricks, and Techniques

Export associative arrays from a CSV

- [David] Hi, I'm David Powers and welcome to this week's edition of PHP Tips, Tricks and Techniques, designed to help you become a smarter, more productive PHP developer. This week I'm going to show you how to process a CSV file by exporting each line as an associative array. This not only makes it easier to handle the values extracted from the file, the technique I'm gonna use works on just one line at a time and that greatly reduces the amount of memory required. The exercise files for this video contain this file, students.csv and if I scroll down to the bottom, you'll see why memory is such an issue. We've got ten thousand lines in here. The first line contains column headers, and we can use those as the keys for the associative arrays. That's a fairly simple part of the operation, because PHP has a built-in function called array_combine that will handle that for us. The problem is the size of the file. With so many lines, it's more than a megabyte, so if we loop through it to…

Contents