What is the fastest way to trim blank lines from beginning and end of array?
- by Edward Tanguay
This script:
<?php
$lines[] = '';
$lines[] = 'first line ';
$lines[] = 'second line ';
$lines[] = '';
$lines[] = 'fourth line';
$lines[] = '';
$lines[] = '';
$lineCount = 1;
foreach($lines as $line) {
echo $lineCount . ': [' . trim($line) . ']<br/>';
$lineCount++;
}
?>
produces this output:
1: []
2: [first line]
3: [second line]
4: []
5: [fourth line]
6: []
7: []
What is the fastest, most efficient way to change the above script so that it also deletes the preceding and trailing blank entries but not the interior blank entries so that it outputs this:
1: [first line]
2: [second line]
3: []
4: [fourth line]
I could use the foreach loop but I imagine there is a way with array_filter or something similar which is much more efficient.