Home  >  Article  >  Backend Development  >  How to clear empty value elements in an array in php

How to clear empty value elements in an array in php

青灯夜游
青灯夜游Original
2021-06-01 16:55:407333browse

php method to clear null value elements in an array: 1. Use the foreach or while syntax structure to traverse the array and delete the null value elements in the array one by one; 2. Use the array_filter() function and use the callback function to filter the array element, if there is no callback function, the default is to delete the null value in the array.

How to clear empty value elements in an array in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

php clears the array Null value elements

#Method 1: Use foreach or while syntax structure to traverse the array, and determine and delete the null value elements in the array one by one

<?php   
foreach( $arr as $k=>$v){   
    if( !$v )   
        unset( $arr[$k] );   
}   
?>

Convert $arr to an object first, and then use the characteristics of the object to delete it, because: foreach copies the array of the current operation. Every time a foreach is operated, a variable is copied. If there are too many foreach in the page, It will be a big consumption.

Method 2: Use the array_filter() function

The function of the array_filter function is to use the callback function to filter the array. I always thought that the callback function can be used to process it, but it turns out that I didn't find another sentence in the manual. If there is no callback function, the default is to delete items with a false value in the array.

<?php   

$entry = array(   
             0 => &#39;foo&#39;,   
             1 => false,   
             2 => -1,   
             3 => null,   
             4 => &#39;&#39;  
          );   

print_r(array_filter($entry));   
?>

The output value is:

Array   
(   
    [0] => foo   
    [2] => -1   
)

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to clear empty value elements in 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