PHP to determine whether an array is empty?

Source: Internet
Author: User

After Google, we sorted out the following methods:
I. For Loop
The simplest and most direct method is to use a for loop to traverse the array. An array with known dimensions can be judged, but what if it is an unknown multi-dimensional array?

Ii. implode ();
Use implode () to output the array as a string and determine whether the output string is null. It seems to be a good method at the beginning, but unfortunately it keeps up with 1.1. It won't work for arrays above two dimensions. For example:

$ Arr = array (Array (), array (), array ());
$ STR = implode (',', $ ARR );

If (empty ($ Str) echo "null ";
Else echo "not empty ";

Obviously, $ arr is a two-dimensional array containing three empty arrays. It should be empty, but the output is indeed non-empty. Failed.

3. Count ();

$ Arr = array ("","","");
Echo count ($ ARR );

4. in_array ('', $ ARR ));

$ Arr = array ("D", "S ","");
Echo in_array ('', $ ARR );
This can only indicate empty elements in the array, and it cannot be proved that the array is empty. Obviously not.

5. Empty ();
This cpyeh is similar to the previous methods.

$ Arr = array ("","","");
If (empty ($ ARR) echo "null ";
Else echo "not empty ";

The result is not empty.

6. Use strlen (). If there is no content, it seems that the length is 1.

Add print_r ($ ARR) to the preceding example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.