Search code examples
phpcallbackanonymous-functionarray-map

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?


Solution

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