在 PHP 中删除空数组元素

phpserver side programmingprogramming更新于 2025/8/25 4:07:17

要在 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 值的对应数组。


相关文章