Using array_filter() with a callback that returns an array

1.2k views Asked by At

I have data like this:

a|b|c|d|e|f|g
h|i|j|k|l|m|n
o|p|q|r|s|t|u

I can easily use explode("\n", $data) to get an array of all the lines (this is a ~4.0GB file), but now I want to make it a multi-dimensional array by using explode() based on the vertical pipe. Here is what I tried:

$data = explode("\n", './path-to-file.txt');
$results = array_filter($data, function ($el) {
   return explode('|', $el);
});

However, this results in a single-dimensional array with the original line in string form.

How can I use array_filter() with a callback that happens to return an array?

Edit: I could use foreach($data as $datum) and do the explode() that way, but when I tried that, I utilized about four times the amount of RAM than the size of the file, and that is not desirable. This seems like a perfect opportunity to use a callback function, but I seemingly cannot do that with array_filter().

1

There are 1 answers

5
AbraCadaver On BEST ANSWER

array_filter() filters elements to include or exclude them and expects true to include the element or false to exclude. Use array_map():

$data = explode("\n", './path-to-file.txt');
$results = array_map(function ($el) {
   return explode('|', $el);
}, $data);

A more memory efficient way would be to read line by line:

if(($handle = fopen("./path-to-file.txt", "r")) !== false) {
    while(($results[] = fgetcsv($handle, 0, "|")) !== false) {}
}