1

I want to remove empty elements from an array. I have a $_POST-String which is set to an array by explode(). Then I'am using a loop to remove the empty elements. But that does not work. I also tried array_filter(), but with no succes. Can you help me? See Code below:

$cluster = explode("\n", $_POST[$nr]);

     print_r ($cluster);
     echo "<br>";

  for ($i=0 ; $i<=count($cluster);$i++) 
    {
      if ($cluster[$i] == '') 
       {
         unset ( $cluster[$i] );
       }
    }

     print_r ($cluster);
     echo "<br>";

Result:

Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => [5] => )

Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => ) 
Crayl
  • 1,883
  • 7
  • 27
  • 43

3 Answers3

4

Empty elements can easily be removed with array_filter:

$array = array_filter($array);

Example:

$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
    [item_1] => hello
    [item_3] => world
)
*/
  • @teuneboon: He didn't post the code for that attempt, so it's possible he/she make a mistake. –  Apr 08 '11 at 19:03
  • cool, i was about to post `array_filter(function($x){return $x;}, $_POST[$nr]);` but i didnt realize there was a 'default' function like that – jon_darkstar Apr 08 '11 at 19:03
  • if integer 0 is a valid value, then see this : http://stackoverflow.com/questions/3654295/remove-empty-array-elements/3654335#3654335. By default array_filter would remove all 0/False/null/''. See this : http://php.net/manual/en/function.array-filter.php#example-4111 – understack May 21 '11 at 21:10
1

What if you change:

for ($i=0 ; $i<=count($cluster);$i++) { if ($cluster[$i] == '') { unset ( $cluster[$i] ); } }

to

for ($i=0 ; $i<=count($cluster);$i++) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } }
teuneboon
  • 4,034
  • 5
  • 23
  • 28
1

The problem ist that the for loop condition gets evaluated on every run.

That means count(...) will be called multiple times and every time the array shrinks.

The correct way to do this is:

$test = explode("/","this/is/example///");
print_r($test);
$arrayElements = count($test);
for($i=0;$i<$arrayElements;$i++)
    if(empty($test[$i])
        unset($test[$i]);

print_r($test);

An alternative way without an extra variable would be counting backwards:

$test = explode("/","this/is/example///");
print_r($test);
for($i=count($test)-1;$i>=0;$i--)
    if(empty($test[$i])
        unset($test[$i]);

print_r($test);
dog
  • 390
  • 2
  • 8
  • Thanks. I've now solved this with trim & a while loop $i = 0; $v = count($cluster); while ( $i<$v) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } $i++; } – Crayl Apr 08 '11 at 19:15