Home > Backend Development > PHP Problem > How to delete blank elements in an array in php

How to delete blank elements in an array in php

王林
Release: 2023-03-11 09:00:01
Original
1626 people have browsed it

The way PHP deletes blank elements in an array is to first judge the array. Then iterate through the elements in the array one by one to determine whether the element is null. Finally, use the unset function to delete blank elements.

How to delete blank elements in an array in php

The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.

The unset function can release the given variable. By using this function, we can delete blank elements from the array without any worries. Let's take a look at how to delete blank elements in an array.

Implementation code:

/*
 *$arr = array('', 'test', '   ');
 *dump($arr);输出结果中将只有 'test'
 */
public function removeEmpty($arr, $trim = TRUE)
{
    foreach ($arr as $key => $value){
        if (is_array($value)){
            self::removeEmpty($arr[$key]);
        }
        else{
            $value = trim($value);
            if ($value == ''){
                unset($arr[$key]);
            }
            elseif ($trim){
                $arr[$key] = $value;
            }
        }
    }
}
Copy after login

You can save the above code locally and see the effect by running it locally.

Related video tutorial sharing: php video tutorial

The above is the detailed content of How to delete blank elements in an array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template