PHP to determine whether an array is empty Code 1. the simplest and most direct method of the for loop is to use the for loop to traverse the array. An array with known dimensions can be judged, but what if it is an unknown multi-dimensional array? 2. 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 first, but it is a pity to keep up with the 1.1 PHP code to determine whether an array is empty
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 ());
$ 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 ();
I have to admit that this function was the first one I thought of. There are also a lot of online users who thought this was the answer and thought it had solved the problem. However, please refer to the following example:
$ Arr = array ("","","");
Echo count ($ arr );
I don't need to say anything about this method anymore.
4. in_array ('', $ arr ));
Let's just look at the example:
$ 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.
You can add print_r ($ arr) to the preceding example...
Basically, what cpyeh can think of is what we can find on the internet. What I don't understand is that some people will mention is_array () on the internet. it may be that we don't know much about php and need to turn over the manual. Unfortunately, we still cannot find a perfect solution. However, for general applications, the first or second method should be satisfied, and cpyeh selects the second method for convenience. If you have any questions about the above examples, please leave a message here to communicate with each other.