Home >Backend Development >PHP Problem >Determine whether the array is empty php
In PHP, there are two ways to determine whether an array is empty. Two methods will be introduced here.
Method 1: Use the count() function to determine the number of array elements
PHP’s built-in count() function can return the number of all elements in an array. We can use this function to determine the number of elements in an array. Whether the array is empty.
The following is a sample code:
<?php $array = array(); if(count($array) == 0){ echo "数组为空"; } else { echo "数组不为空"; } ?>
In the above code, we first define an array named $array, and there are no elements in the array. Then use the count() function to determine the number of elements in the $array array. If the number is 0, the array is empty.
If the $array array contains elements, the count() function will return the number of elements in the array, and we can use this to determine that the array is not empty.
Method 2: Use the empty() function to determine whether the array is empty
The empty() function can determine whether a string, array or object is empty, but it should be noted that empty( ) function determines that an object is empty not based on whether its attributes are empty, but based on whether the object is invalid. Therefore, this article only introduces the array determination method of the empty() function.
To determine whether the array is empty, we can directly use the empty() function:
<?php $array = array(); if(empty($array)){ echo "数组为空"; } else { echo "数组不为空"; } ?>
In the above code, we only need to use the $array array as a parameter of the empty() function. If If the $array array is empty, the empty() function returns true, otherwise it returns false.
Summary:
In PHP, we can determine whether an array is empty through the count() function and the empty() function. Among them, the count() function can return the number of array elements; the empty() function can be used to determine whether a string, array or object is empty. Depending on actual needs, we can flexibly choose to use different methods.
The above is the detailed content of Determine whether the array is empty php. For more information, please follow other related articles on the PHP Chinese website!