Array empty check in php

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.


Main Notes:

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

Take these arrays for example:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don't use it thereafter, such as:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).


Here's an approach which uses very little code to check if an array has values:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    An empty array can sometimes cause software crash or unexpected outputs. To avoid this, it is better to check whether an array is empty or not beforehand. There are various methods and functions available in PHP to check whether the defined or given array is an empty or not. Some of them are given below:

    1. Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.

      Syntax:

      bool empty( $var )

      Example:

      $empty_array = array();

      if(!empty($non_empty_array))

          echo "Given Array is not empty
      "
      ;

      if(empty($empty_array))

          echo "Given Array is empty";

      ?>

      Output:

      Given Array is not empty 
      Given Array is empty

    2. Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.

      Syntax:

      int count( $array_or_countable )

      Example:

      $empty_array = array();

      if(count($empty_array) == 0)

          echo "Array is empty";

      else

          echo "Array is non- empty";

      ?>

    3. Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.

      Example:

      $empty_array = array();

      if( sizeof($empty_array) == 0 )

          echo "Empty Array";

      else

          echo "Non-Empty Array";

      ?>

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


    How check if array is empty PHP?

    Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array. ... .
    Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty..

    How do you check if an array is empty?

    To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

    Is empty array falsey PHP?

    For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.

    What does empty check in PHP?

    PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0. 0.0.