How to remove null values ​​from php array

青灯夜游
Release: 2023-03-16 06:00:02
Original
3538 people have browsed it

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]);}".

How to remove null values ​​from php array

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$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);
?>
Copy after login

How to remove null values ​​from php array

##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:

  • Syntax format 1:

  • foreach ($array as $value){
        语句块;
    }
    Copy after login
Traverse the given

$array Array, assign the value of the current array to $value in each loop.

  • Syntax format 2:

  • foreach ($array as $key => $value){
        语句块;
    }
    Copy after login
    Traverse the given

    $array array, and in each loop The value of the current array is assigned to $value, and the key name is assigned to $key.

    Recommended learning: "

    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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!