Home  >  Article  >  Backend Development  >  php数组去除空值函数分享_PHP

php数组去除空值函数分享_PHP

WBOY
WBOYOriginal
2016-05-31 13:17:32885browse

对于一个一维的php数组,如何清除其中值为空的元素呢?直接的办法是foreach循环一下,一个个判断排除。不过这个方法还是略显复杂,下面分享一下今天看到的一个方法,非常简洁

代码如下:


/**
 * 方法库-数组去除空值
 * @param string $num  数值
 * @return string
 */
public function array_remove_empty(&$arr, $trim = true) {
    if (!is_array($arr)) return false;
    foreach($arr as $key => $value){
        if (is_array($value)) {
            self::array_remove_empty($arr[$key]);
        } else {
            $value = ($trim == true) ? trim($value) : $value;
            if ($value == "") {
                unset($arr[$key]);
            } else {
                $arr[$key] = $value;
            }
        }
    }
}

是不是非常实用的函数呢,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn