Home > Article > Backend Development > How to check if an array is empty using PHP? (code example)
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.
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 )
Let’s take an example to see how to use the empty() function to check whether the array is empty.
<?php header("content-type:text/html;charset=utf-8"); // 声明数组并初始化它 $array1 = array('0' => 'hello','1' => 'php'); // 声明空数组 $array2 = array(); // 检查数组的条件是否为空 if(!empty($array1)) echo "给定数组array1不为空 <br>"; if(empty($rray2)) echo "给定数组array2 为空"; ?>
Output:
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 )
Let’s take an example to see how to use the count() function to check whether the array is empty.
<?php header("content-type:text/html;charset=utf-8"); // 声明一个空数组 $empty_array = array(); // 检查数组是否为空 if(count($empty_array) == 0) echo "数组为空"; else echo "数组不为空"; ?>
Output:
数组为空
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.
<?php header("content-type:text/html;charset=utf-8"); // 声明一个空数组 $empty_array = array(); if( sizeof($empty_array) == 0 ) echo "数组为空"; else echo "数组不空"; ?>
Output:
数组为空
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!