What is the fastest way to trim blank lines from beginning and end of array?
Posted
by Edward Tanguay
on Stack Overflow
See other posts from Stack Overflow
or by Edward Tanguay
Published on 2010-05-02T10:44:01Z
Indexed on
2010/05/02
10:47 UTC
Read the original article
Hit count: 282
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.
© Stack Overflow or respective owner