從 PHP 中移除空陣列元素


要在 PHP 中移除空陣列元素,程式碼如下 −

樣例

 即時演示

<?php
   $my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
   foreach($my_array as $key => $val)
   if(empty($val))
      unset($my_array[$key]);
   echo "After removing null values from the array, the array has the below elements -";
   foreach($my_array as $key => $val)
   echo ($my_array[$key] ."<br>");
?>

輸出

After removing null values from the array, the array has the below elements -This
91
102
is
a
sample

定義了一個包含字串、數字和‘null’值的陣列。使用 ‘foreach’ 迴圈迭代這些元素,如果一個值為 null,則從陣列中刪除該元素。重新展示相關陣列,其中不包含 null 值。

更新於: 02-Jul-2020

579 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告