简体   繁体   English

无法从数组中删除空元素

[英]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(). 我有一个$ _POST-String,它由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. 我也尝试了array_filter(),但是没有成功。 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_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. 问题是for循环条件在每次运行时都会得到评估。

That means count(...) will be called multiple times and every time the array shrinks. 这意味着count(...)将在数组每次收缩时被多次调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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