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

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

PHPz
PHPzOriginal
2023-04-19 11:38:42646browse

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)

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)

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!

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