Home > Backend Development > PHP Problem > How to remove blank values ​​​​from an array in php

How to remove blank values ​​​​from an array in php

PHPz
Release: 2023-04-19 14:07:45
Original
673 people have browsed it

When developing PHP programs, you often encounter situations where you need to process arrays. However, sometimes "blank values" (i.e. NULL values ​​or empty strings) appear in the array, and these values ​​will affect the processing and display of data. This article will show you how to remove blank values ​​from an array using PHP.

1. Array_filter() function

In PHP, there is a built-in function array_filter(), which can filter the array and filter out the elements that meet the conditions. The first parameter of this function is the array to be filtered, and the second parameter is the filter function. Each element in the array will be passed into the filter function as a parameter. If the return value is false, it will be filtered out.

Use the array_filter() function to easily remove blank values ​​​​in the array. Examples are as follows:

$original_array = array('foo', NULL, 'bar', '', 'baz');

// 定义一个匿名函数,用于筛选非空元素
$trimmed_array = array_filter($original_array, function($value) {
    return $value !== '' && $value !== NULL;
});

// 输出结果
print_r($trimmed_array); // 输出:Array([0] => foo [2] => bar [4] => baz)
Copy after login

2. foreach loop

In addition to using the array_filter() function, we can also use the foreach loop to traverse the array, and Remove the blank values:

$original_array = array('foo', NULL, 'bar', '', 'baz');

$trimmed_array = array();
foreach ($original_array as $value) {
    if ($value !== '' && $value !== NULL) {
        $trimmed_array[] = $value;
    }
}

print_r($trimmed_array); // 输出:Array([0] => foo [2] => bar [4] => baz)
Copy after login

3. Conclusion

Whether you use the array_filter() function or the foreach loop to remove the blank values ​​​​in the array , all have their uses in actual development. It should be noted that when using the array_filter() function, the second parameter is the filter function, which can be a defined function name or an anonymous function. When processing data, we should try our best to ensure the integrity and correctness of the data. Removing blank values ​​​​in the array is a good operation.

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

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