首页  >  文章  >  后端开发  >  php怎么去掉数组中的空元素

php怎么去掉数组中的空元素

藏色散人
藏色散人原创
2021-06-24 09:38:203060浏览

php去掉数组中的空元素的方法:1、使用“function myfunction($v) {...}”方法去除空元素;2、使用“foreach ($urlArr as $key => $val) {...}”方法去掉数组中的空元素。

php怎么去掉数组中的空元素

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php怎么去掉数组中的空元素?

PHP数组去除空元素的方法

去除空元素方法一:(保持键值不变)

原数组:

<?php
Array(
 [0] => sdfdsdsdsfrrrrrrr
 [1] => fdsfdsdsfds
 [2] => fdsfdsdsfdsds 
 [3] => fdsdsfdsfds 
 [4] => 
 [5] =>
 [6] =>
 [7] => fdsfdsfdsfds
 [8] => fdsfdsfdsfdsfdsfsd 
 [9] => ssssssss
 [10] => 
 [11] => sssssssssssssssssssss)
 ?>

处理之后数组

<?php
Array( 
[0] => sdfdsdsdsfrrrrrrr 
[1] => fdsfdsdsfds
[2] => fdsfdsdsfdsds 
[3] => fdsdsfdsfds 
[7] => fdsfdsfdsfds 
[8] => fdsfdsfdsfdsfdsfsd 
[9] => ssssssss 
[11] => sssssssssssssssssssss)
?>

使用方法:

<?php
function myfunction($v) {
    if ($v != "") {
        return true;
    }
    return false;
}
print_r(array_filter($urlArr, "myfunction"));
?>

去除空元素方法二:(键值自增)

原数组:

<?php
Array
(
[0] => sdfdsdsdsfrrrrrrr
[1] => fdsfdsdsfds
[2] => fdsfdsdsfdsds
[3] => fdsdsfdsfds
[4] =>
[5] =>
[6] =>
[7] => fdsfdsfdsfds
[8] => fdsfdsfdsfdsfdsfsd
[9] => ssssssss
[10] =>
[11] => sssssssssssssssssssss
)

处理之后数组:

Array
(
[0] => sdfdsdsdsfrrrrrrr
[1] => fdsfdsdsfds
[2] => fdsfdsdsfdsds
[3] => fdsdsfdsfds
[4] => fdsfdsfdsfds
[5] => fdsfdsfdsfdsfdsfsd
[6] => ssssssss
[7] => sssssssssssssssssssss
)

使用方法:

$arr = array();
    foreach ($urlArr as $key => $val) {
        if (empty($val)) {
            continue;
        }
        $arr[] = $val;
    }

推荐学习:《PHP视频教程

以上是php怎么去掉数组中的空元素的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn