繁体   English   中英

无法从数组中删除空元素

[英]Can't remove empty elements from array

我想从数组中删除空元素。 我有一个$ _POST-String,它由explode()设置为数组。 然后,我使用循环来删除空元素。 但这不起作用。 我也尝试了array_filter(),但是没有成功。 你能帮助我吗? 请参见下面的代码:

$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>";

结果:

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

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

空元素可以使用array_filter轻松删除:

$array = array_filter($array);

例:

$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
    [item_1] => hello
    [item_3] => world
)
*/

如果您更改:

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

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

问题是for循环条件在每次运行时都会得到评估。

这意味着count(...)将在数组每次收缩时被多次调用。

正确的方法是:

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

没有额外变量的另一种方法是倒数:

$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