1

I have the following array:

Array 
(
[0] => 
[1] => 
[2] => apple
[3] => 
[4] => orange
[5] => strawberry
[6] => 
)

How can I remove the empty items from the beginning and the end, but not from the inside? The final array should look like this:

Array 
(
[0] => apple
[1] => 
[2] => orange
[3] => strawberry
)

7 Answers 7

10

Here's a convenient way:

while (reset($array) == '') array_shift($array);
while (end($array) == '') array_pop($array);

See it in action.

Obligatory comment: I 'm using a loose comparison with the empty string because it looks like what you intend given your example. If you want to be more picky about exactly which elements to remove then please customize the condition accordingly.

Update: bonus hallmark PHP ugly code which might be faster

It occurred to me that if there are lots of empty elements at the beginning and end of the array the above method might not be the fastest because it removes them one by one, reindexing the array in each step, etc. So here's a solution that works for any array and does the trimming in just one step. Warning: ugly.

$firstNonEmpty = 0;
$i = 0;
foreach ($array as $val) {
    if ($val != '') {
        $firstNonEmpty = $i;
        break;
    }
    ++$i;
}

$lastNonEmpty = $count = count($array);
end($array);
for ($i = $count; $i > 0; --$i) {
    if (current($array) != '') {
        $lastNonEmpty = $i;
        break;
    }
    prev($array);
}

$array = array_slice($array, $firstNonEmpty, $lastNonEmpty - $firstNonEmpty);

See it in action.

Sign up to request clarification or add additional context in comments.

7 Comments

Clean and sexy. Work for first and last empty only. But if you look closer, [0] and [1] are empty and disappear from the "should look like this"... maybe a mistake ?
@DavidBélanger: Huh, what's a mistake?
Wow I like this much more than my suggestion! +1 sir
@Rocket Look the OP question. [0] and [1] are empty and [2] is apple. If you look to the "array should now look..." apple is [0]. It mean that [0] AND [1] are empty but are gone. So it's not only first and last. But in the text he say first and last line. That's what is a mistake, mistype or misexample...
@DavidBélanger: The words "first" and "last" aren't used anywhere. The OP asked to remove ALL blanks form the "beginning" and "end".
|
1

There ya go :

$Array = array('', Allo, '');

if(isset($Array[0]) && empty($Array[0])){
    array_pop($Array);
}

$C = count($Array)-1;
if(isset($Array[$C]) && empty($Array[$C])){
    array_shift($Array);
}

It will remove first and last empty only row.

If you want to remove all first and last but only empty you'll need to do this :

$Array = array('', Allo, '', '', 'Toc', '', '', '');

$i=0;
foreach($Array as $Key => $Value){
    if(empty($Value)){
        unset($Array[$Key]);
    } else {
        break;
    }
    $i++;
}

$Array = array_reverse($Array);
$i=0;
foreach($Array as $Key => $Value){
    if(empty($Value)){
        unset($Array[$Key]);
    } else {
        break;
    }
    $i++;
}

$Array = array_reverse($Array);

4 Comments

Shouldn't this be in some kind of loop?
@Rocket Why ? If you only want to remove first and last if empty, no, because you already know witch one is first and last so you only need to check if they are empty. If you want to remove ALL first and last who's empty, then yes you need a loop, see my second script.
The Original Post clearly shows two items being removed from the beginning of the array, not just one. Your edit addresses this, but just backing up @Rocket on this one...
The array is numerically indexed.
0

You can use

array_pop($array); // remove the last element
array_shift($array); // remove the first element

You can do some simple checking before to make sure the first and/or last index is empty

Comments

0

Here's another method:

<?php

$array = array('', '', 'banana', '', 'orange', '', '', '');

while ($array[0] == '')
{
    array_shift($array);
}

$count = count($array);

while ($array[$count - 1] == '')
{
    array_pop($array);
    $count--;
}

print_r($array);

?>

3 Comments

Like other solutions, this will not work if the array is not numerically indexed.
While your statement is totally true, his array is numerically indexed.
@Dale: I think it was just an FYI :-P
0

The following snippet will do the job:

function removeStartingEmptyIndexes($array)
{
  foreach($array as $i => $item)
  {
    if(!empty($item)) {
      break;
    }
    else
    {
      unset($array[$i]);
    }
  }

  return $array;
}

function trimEmptyIndexes($array)
{
  return array_reverse(removeStartingEmptyIndexes(array_reverse(removeStartingEmptyIndexes($array))));
}

$array = array("", "", "apple", "orange", "", "", "", "lemon", "", "");

$array = trimEmptyIndexes($array);

Just call "trimEmptyIndexes($array)"

Comments

-1

try this

foreach ($original_array as $index => $val) {
  if (is_empty($val)) {
    unset($original_array [$index]);
  } else {
    break;
  }

}

1 Comment

Except he wants the blank between "apple" and "orange" to still be there.
-1
while(strlen($array[0])==0)
    unset(array[0]);

$doLoop=(strlen($array[ count(array)-1 ])==0);
while ($doLoop){
    unset($array[ count(array)-1 ]);
    $doLoop=(strlen($array[ count(array)-1 ])==0);
}

8 Comments

Right. Why prefer a solution that works in cars and planes when you can have a solution that works in just cars indeed.
His array is numerically indexed.
@Jon, generally speaking I agree that your way is better - but this is still quite a valid response to the question at hand.
@Dale Yes but the solution should become a function and / or work everywhere. Jon solution is perfect because it require no numerical index or not.
Yes I upvoted his answer, I am just replying to all of his comments that the array is indeed numerically indexed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.