Method: 1. Loop through the array with the syntax "foreach($arr as $k=>$v){}"; 2. In the loop body, use "==" to determine whether the element value is null. , if so, use unset() to delete the element, the syntax is "if($v==null){unset($arr[$k]);}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Remove null from the php array Value method
Implementation method:
Use the foreach statement to loop through the array
In the loop body, determine whether the array element is null. If so, use unset() to delete the element.
unset() function is used to destroy the given variable, unset($ arr[$key])
.
Implementation example:
<?php header('content-type:text/html;charset=utf-8'); $arr = array(1,2,null," ",null,"",3,4); var_dump($arr); foreach ($arr as $key => $value){ if($value==null){ unset($arr[$key]); } } var_dump($arr); ?>
##Expand knowledge:
foreach The statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts. When the foreach statement loops, the pointer inside the array will move forward one step, so that the next array element will be obtained in the next loop until the end of the array is traversed, the traversal stops and the loop exits. The foreach statement has two syntax formats:foreach ($array as $value){ 语句块; }
$array Array, assign the value of the current array to
$value in each loop.
foreach ($array as $key => $value){ 语句块; }
$array array, and in each loop The value of the current array is assigned to
$value, and the key name is assigned to
$key.
PHP Video Tutorial"
The above is the detailed content of How to remove null values from php array. For more information, please follow other related articles on the PHP Chinese website!