Home > Article > Backend Development > php remove null values from array
php method to delete null values in an array: 1. Remove null value elements in the array through foreach or while; 2. Remove null value elements in the array through the array_filter function.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
How to delete null values in an array in php ?
PHP removes null value elements from arrays (array_filter)
I am ashamed to say that in the past, when removing null values from arrays, foreach or while were forced. Use these two A syntax structure to delete empty elements in the array. The simple code is as follows:
<?php foreach($arr as $k=>$v){ if(!$v) unset($arr[$k]); }
It turns out that this processing is not efficient if the array is too large. Because foreach copies the currently operated array, each foreach operation copies a variable. If there are too many foreach on the page, it will be a big waste.
When I was wandering around on the Internet, I saw someone prompting me to use array_filter, so I opened the manual and looked at it, and found that I had been guarding a treasure mountain but didn't know how to use it.
The function of the array_filter function is to use the callback function to filter the array. If there is no callback function, the default is to delete items with a false value in the array. The following example:
<?php $entry = array( 0 => 'foo', 1 => false, 2 => -1, 3 => NULL, 4 => '' ); print_r(array_filter($entry));
The output value is:
Array ( [0] => foo [2] => -1 )
Recommendation: The two most important chapters in PHP should be array operations and string operations. You must be proficient in the functions in these two chapters. Just check the rest when you use them.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of php remove null values from array. For more information, please follow other related articles on the PHP Chinese website!