2

I'm using this code to get an array from a csv file:

array_map('str_getcsv', 'file.csv')

But how do I set delimeter for str_getcsv() when using it in array_map function?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Einius
  • 1,352
  • 2
  • 20
  • 45

1 Answers1

13

If you need to attach additional parameters to a function that requires a callable the easiest way it to just pass in a wrapper function with your parameters pre-defined

$array = array_map(function($d) {
    return str_getcsv($d, "\t");
}, file("file.csv"));

Alternatively you can pass in parameters using the use() syntax with the closure.

$delimiter = "|";
$array = array_map(function($d) use ($delimiter) {
    return str_getcsv($d, $delimiter);
}, file("file.csv"));

Another fun thing that can be done with this technique is create a function that returns functions with predefined values built in.

function getDelimitedStringParser($delimiter, $enclosure, $escapeChar){
    return function ($str) use ($delimiter, $enclosure, $escapeChar) {
        return str_getcsv($str, $delimiter, $enclosure, $escapeChar);
    };
}

$fileData = array_map("trim", file("myfile.csv"));
$csv = array_map(getDelimitedStringParser(",", '"', "\\"), $fileData);
Orangepill
  • 24,500
  • 3
  • 42
  • 63