Home  >  Article  >  Backend Development  >  How to remove spaces from php array

How to remove spaces from php array

coldplay.xixi
coldplay.xixiOriginal
2020-08-15 14:54:414709browse

How to remove spaces from PHP arrays: Use the function [array_filter()] to remove spaces from a one-dimensional array. The code is [function filter_array($arr, $values ​​= ['', null, false, 0, '0',[]])].

How to remove spaces from php array

How to remove spaces from an array in php:

To remove empty values ​​from an array in php, you can use array_filter()This function can only work on one-dimensional arrays. Once you need to remove empties from a multi-dimensional array, it will not work, and the removed empties also include (int)0, (string)0. Use it There is still something wrong!

The custom function to remove a value in the array defaults to a null value. It can be used for both one-dimensional arrays and multi-dimensional arrays!

/**
 * 去除多维数组中的空值
 * @author 
 * @return mixed
 * @param $arr 目标数组
 * @param array $values 去除的值  默认 去除  '',null,false,0,'0',[]
 */
function filter_array($arr, $values = ['', null, false, 0, '0',[]]) {
    foreach ($arr as $k => $v) {
        if (is_array($v) && count($v)>0) {
            $arr[$k] = filter_array($v, $values);
        }
        foreach ($values as $value) {
            if ($v === $value) {
                unset($arr[$k]);
                break;
            }
        }
    }
    return $arr;
}

Related learning recommendations: php programming (video)

The above is the detailed content of How to remove spaces from php array. For more information, please follow other related articles on the PHP Chinese website!

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