简体   繁体   中英

Can't remove empty elements from array

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] => ) 

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
)
*/

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] ); } }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM