How to check if an array is empty using PHP? (code example)

青灯夜游
Release: 2023-04-05 19:04:02
Original
2986 people have browsed it

Empty arrays can sometimes cause program crashes or unexpected output. To avoid this, it's better to check if an array is empty beforehand. There are various methods and functions in PHP that can be used to check whether a defined or given array is empty. The following article will introduce you to several of these methods, I hope it will be helpful to you.

How to check if an array is empty using PHP? (code example)

Method 1: Use the empty() function

The empty() function can be used to determine the Determine whether the variable is empty. This function does not return a warning if the variable does not exist.

Basic syntax:

empty( $var )
Copy after login

Let’s take an example to see how to use the empty() function to check whether the array is empty.

 'hello','1' => 'php'); // 声明空数组 $array2 = array(); // 检查数组的条件是否为空 if(!empty($array1)) echo "给定数组array1不为空 
"; if(empty($rray2)) echo "给定数组array2 为空"; ?>
Copy after login

Output:

How to check if an array is empty using PHP? (code example)

Method 2: Use count() function

The count() function is used to count all elements in an array. If the number of elements in the array is zero, then it will display an empty array.

Basic syntax:

count( $array_or_countable )
Copy after login

Let’s take an example to see how to use the count() function to check whether the array is empty.

Copy after login

Output:

数组为空
Copy after login
Copy after login

Method 3: Using sizeof() function

sizeof() function is used to check the array the size of. If the size of the array is zero, the array is empty, otherwise the array is not empty.

Let’s take an example to see how to use the sizeof() function to check whether the array is empty.

Copy after login

Output:

数组为空
Copy after login
Copy after login

Related video tutorial recommendation: "PHP Tutorial"

The above is the entire content of this article, I hope it can be helpful to everyone learning helps. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to check if an array is empty using PHP? (code example). 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
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!