Master the tips for deleting null values ​​​​in arrays in PHP

autoload
Release: 2023-03-08 19:22:02
Original
2672 people have browsed it

Method 1: Use loops (this article takes foreach as an example)

The syntax structure is as follows:

foreach (array_expression as $value)
Copy after login
foreach (array_expression as $key => $value)
Copy after login

For specific usage, please refer to: "php foreach Detailed usage explanation》, the specific code is as follows:

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

This method is relatively simple and easy for beginners to understand, but it is more complex and consumes more memory, so it is generally not recommended.

Method 2: Use the array_filter() function

The syntax structure is as follows:

array_filter( array $array [, callable $callback [, int $flag = 0  ]] ) : array
Copy after login

Pass each value in the array array to the callback function in turn . If the callback function returns true, the current value of the array array will be included in the returned result array, and the key names of the array will remain unchanged.

  • # Array The array of circulating

  • # 没有 没有callback function will delete all entries with the equivalent value of FALSE in array .

  •            flagDetermines the parameter form received by callback: (1) ARRAY_FILTER_USE_KEY - callback accepts the key name as the only parameter.

                                                                                    (2) ARRAY_FILTER_USE_BOTH - callback accepts both key name and key value.

Return value: filtered array.

The specific code is as follows:

<?php   
$arr = array(   
             0 => &#39;hello&#39;,   
             1 => false,   
             2 => -1,   
             3 => null,   
             4 => &#39;&#39;  
          );   
  echo "<pre class="brush:php;toolbar:false">";
  var_dump(array_filter($arr));   
?>
Copy after login

The running results are as follows:

/*   array(2) {
    [0]=>
    string(5) "hello"
    [2]=>
    int(-1)
  } */
Copy after login

Recommendation: php video tutorial php tutorial

The above is the detailed content of Master the tips for deleting null values ​​​​in arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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