Method 1: Use loops (this article takes foreach as an example)
The syntax structure is as follows:
foreach (array_expression as $value)
foreach (array_expression as $key => $value)
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] ); } ?>
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
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
.
flag
Determines 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 => 'hello', 1 => false, 2 => -1, 3 => null, 4 => '' ); echo "<pre class="brush:php;toolbar:false">"; var_dump(array_filter($arr)); ?>
The running results are as follows:
/* array(2) { [0]=> string(5) "hello" [2]=> int(-1) } */
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!