Determine if an array is empty code in PHP
one, for loop
The simplest and most straightforward method is to iterate through the array with a for loop. The array of known dimensions can be judged, but what if it is an unknown multidimensional array?
second, implode ();
use implode () to output the array as a string to determine if the output is empty. It seems like a good way to start at first, but as with a little bit more than two-dimensional arrays. As an example:
$arr = Array (array (), array (), array ());
$str = Implode (', ', $arr);
if (empty ($STR)) echo "null";
else echo "non-null";
It is obvious that $arr is a two-dimensional array with three empty arrays, which should also be empty, but the output is indeed non-empty. Judgment failed.
III, COUNT ();
I have to admit that the first thing I think of is this function, online also have many netizens to this when the answer, and thought has solved the problem. But take a look at the following example:
$arr = Array ("", "", "");
echo Count ($arr);
I don't think I need to say much about this method.
iv. In_array (', $arr));
not much to say, or to look at an example:
$arr = Array ("D", "s", "");
Echo In_array (', $arr);
this can only indicate that there are empty elements in the array and cannot prove that the array is empty. It's not obvious.
five, Empty ();
This Cpyeh thinks it's the same as the previous methods .
$arr = Array ("", "", "");
if (empty ($arr)) echo "null";
else echo "non-null";
The result is still non-empty
You can add a sentence print_r ($arr) to the above example;
basically Cpyeh can think of and found on the internet also above these, do not understand is on the net actually someone will mention Is_array (), probably is not very understanding of PHP, need to turn over the manual. Unfortunately, there is no way to find a perfect solution, but for general applications, the first or second should be able to meet, Cpyeh selected a convenient second. If you have questions about the above examples, please feel free to talk to each other.