Einius
Einius

Reputation: 1382

How can I use parameters/arguments for my callback function in array_map()?

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?

Upvotes: 3

Views: 3820

Answers (1)

Orangepill
Orangepill

Reputation: 24645

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);

Upvotes: 14

Related Questions