It’s embarrassing 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 an 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 trove but didn’t know how to use it.
The function of the array_filter function is to use a 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. Example below:
<?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
)
Suggestion: 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. You can check the other ones when you use them.