簡體   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