Home > Backend Development > PHP Problem > How to detect if an array is empty in php

How to detect if an array is empty in php

青灯夜游
Release: 2023-03-16 15:16:01
Original
6594 people have browsed it

3 detection methods: 1. Use "===" to determine whether the specified array is equal to "[]", the syntax is "$arr===[]", if the return value is TRUE, it will be empty , if the return value is FALSE, it is not empty. 2. Use empty() detection, the syntax is "empty($arr)", if the specified array is empty, TRUE is returned, otherwise FALSE is returned. 3. Use count() to get the length of the array, and just check whether the length of the array is greater than 0. The syntax is "count($arr)>0". If it is greater, it is not empty.

How to detect if an array is empty in php

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

php Three methods to detect whether an array is empty (whether it is an empty array)

Method 1: Use the "===" operator to detect

You only need to determine whether the specified array is equal to "[]". If it is equal, it will be an empty array (the return value is TRUE if it is empty, and if the return value is FALSE it is not empty).

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array();
var_dump($arr);
if($arr===[]){
	echo "指定数组为空";
}else{
	echo "指定数组不为空<br";
}
?>
Copy after login

How to detect if an array is empty in php

Method 2: Use the empty() function to detect

The empty() function is used to check whether a variable is empty. Returns TRUE if the specified array is empty, otherwise returns FALSE.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(1,2,3);
var_dump($arr);
if(empty($arr)){
	echo "指定数组为空";
}else{
	echo "指定数组不为空<br";
}
?>
Copy after login

How to detect if an array is empty in php

Method 3: Use the count() function to detect

The count() function can return the array length. If the array length is equal to 0, the specified array is empty; otherwise if the array length is greater than 0, the specified array is not empty

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(1);
var_dump($arr);
if(count($arr)>0){
	echo "指定数组不为空";
}else{
	echo "指定数组为空<br";
}
?>
Copy after login

How to detect if an array is empty in php

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to detect if an array is empty 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