Several ways to determine whether an array is empty in PHP

Source: Internet
Author: User


It's good to judge whether an array is empty or not. Count if the output is 0 then the array is empty and the following is the simple test code. PHP to determine whether the array is empty code

<?php
$arr = Array ();
echo count ($arr);
?>

The array is empty if the output is 0

The PHP judgment array is an empty method 2:empty ($arr);

$arr = Array ("");
$result = Empty ($arr);
$result = False
$arr = Array ();
$result = Empty ($arr);
$result = True

PHP judgment array is null one, for loop

The simplest and most straightforward method is to iterate through the array with a for loop. An array of known dimensions can be judged, but what if it is an unknown multidimensional array?

PHP judgment array is null bis, implode ();

Output the array as a string using implode () to determine whether the output is empty. It seems like a good way to start at first, but just like the one, it's not going to be a two-dimensional array. As an example:

$arr = Array (array (), array (), array ());
$str = Implode (', ', $arr);
if (empty ($STR)) echo "Empty";
else echo "Non-empty";

Obviously $arr is a two-dimensional array of three empty arrays, which should be empty, but the output is really non-empty. Judgment failed.
The PHP judgment array is empty three, count ();

$arr = Array ("", "", "");
echo count ($arr);

PHP judgment array is null four, In_array (', $arr));

$arr = Array ("D", "s", "");
Echo In_array (", $arr);

This only means that there are empty elements in the array and that the array is not empty. Obviously not.

PHP judgment array is empty five, empty ();

This Cpyeh feels similar to the previous methods.

$arr = Array ("", "", "");
if (empty ($arr)) echo "Empty";
else echo "Non-empty";
The result is still not empty

The PHP judgment array is empty six, uses strlen (), does not have the content words as if the length all is 1
We can also add a print_r to the above example ($arr);

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.