views:

99

answers:

2

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.

+1  A: 
// find the first non-blank line
$size = count($lines);
while ($lines[$i] === '' && $i < $size) {
  $i++;
}
$start = $i;

// find the last non-blank line
$i = $size;
while ($lines[$i - 1] === '' && $i > $start) {
  $i--;
}
$end = $i;

// traverse between the two    
for ($i=$start; $i<$end; $i++) {
  echo ($i + $start) . ': [' . trim($lines[$i]) . ']<br/>';
}
cletus
+1  A: 

There's array_slice to create the trimmed array.

function trimLines($lines) {
    $end = count($lines);
    for ($start=0; $lines[$start] === ''; ++$start) {
        if ($start == $end) {
            return array();
        }
    }
    do { --$end; } while ($lines[$end] === '');
    return array_slice($lines, $start, $end-$start+1);
}
outis