3

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?

1 Answer 1

14

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Rizier123 Thanks for the facelift :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.