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()
.
array_filter()
filters elements to include or exclude them and expectstrue
to include the element orfalse
to exclude. Usearray_map()
:A more memory efficient way would be to read line by line: