ChatGPT解决这个技术问题 Extra ChatGPT

How to check whether an array is empty using PHP?

players will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the $gameresult array into $gamerow? In this case it would probably be more efficient to skip exploding the $playerlist if it's empty, but for the sake of argument, how would I check if an array is empty as well?

$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);

Y
Your Common Sense

If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use count():

if (!$playerlist) {
     // list is empty.
}
if (count($playerlist) === 0) {
     // list is empty.
}

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

foreach ($playerlist as $key => $value) {
    if (!strlen($value)) {
       unset($playerlist[$key]);
    }
}
if (!$playerlist) {
   //empty array
}

Shouldn't you just use empty? count will take longer to perform for large arrays.
Done. I also changed it for the fact that you don't have to use isset and stuff.
Given his code example, the variable will be set so you don't need to use empty().
CAREFUL! if(!isset($emptyarray)) is false but if(empty($emptyarray)) returns true. That just nailed me
@Kolob Canyon .. what were you expecting? (assuming that you actually defined an array...). It makes sense to me that something can be 'set' and be 'empty'.
C
Cobby

An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested.

<?php
$playerList = array();
if (!$playerList) {
    echo "No players";
} else {
    echo "Explode stuff...";
}
// Output is: No players

PHP's empty() determines if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).

In most cases you just want to check !$emptyVar. Use empty($emptyVar) if the variable might not have been set AND you don't wont to trigger an E_NOTICE; IMO this is generally a bad idea.


I hope this won't change in some standard... it will be painful
J
James

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.


Thanks very much for this. It was really informative and was able to solve my issue using array_filter()
empty(array()) will always evaludate to FALSE, so adding count(array())==0 will produce true
@mboullouz count(array())==0 is false when there are keys and no values, so this doesn't help in checking for values only. Your statement is correct, but you are forcing a test with count(array()) as the array is of course empty. We need to check when the array has come back from a form or somewhere else to know if it's empty (keys/values) or just has values or not
This solution is perfect for this kind of arrays, for example it helps when you want to validate an input file array_filter($_FILES["documento"]['name'])
I
Ignacio Vazquez-Abrams

count($gamerow['players']) will be 0.


old school da best as always, just check the index of array.
k
kaan_a

I ran the benchmark included at the end of the post. To compare the methods:

count($arr) == 0 : count

empty($arr) : empty

$arr == [] : comp

(bool) $arr : cast

and got the following results

Contents  \method |    count     |    empty     |     comp     |     cast     |
------------------|--------------|--------------|--------------|--------------|
            Empty |/* 1.213138 */|/* 1.070011 */|/* 1.628529 */|   1.051795   |
          Uniform |/* 1.206680 */|   1.047339   |/* 1.498836 */|/* 1.052737 */|
          Integer |/* 1.209668 */|/* 1.079858 */|/* 1.486134 */|   1.051138   |
           String |/* 1.242137 */|   1.049148   |/* 1.630259 */|/* 1.056610 */|
            Mixed |/* 1.229072 */|/* 1.068569 */|/* 1.473339 */|   1.064111   |
      Associative |/* 1.206311 */|   1.053642   |/* 1.480637 */|/* 1.137740 */|
------------------|--------------|--------------|--------------|--------------|
            Total |/* 7.307005 */|   6.368568   |/* 9.197733 */|/* 6.414131 */|

The difference between empty and casting to a boolean are insignificant. I've run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.

#!/usr/bin/php
<?php

//    012345678
$nt = 90000000;

$arr0 = [];
$arr1 = [];
$arr2 = [];
$arr3 = [];
$arr4 = [];
$arr5 = [];

for ($i = 0; $i < 500000; $i++) {
    $arr1[] = 0;
    $arr2[] = $i;
    $arr3[] = md5($i);
    $arr4[] = $i % 2 ? $i : md5($i);
    $arr5[md5($i)] = $i;
}

$t00 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr0) == 0;
}
$t01 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr0);
}
$t02 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr0 == [];
}
$t03 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr0;
}
$t04 = microtime(true);

$t10 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr1) == 0;
}
$t11 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr1);
}
$t12 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr1 == [];
}
$t13 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr1;
}
$t14 = microtime(true);

/* ------------------------------ */

$t20 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr2) == 0;
}
$t21 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr2);
}
$t22 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr2 == [];
}
$t23 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr2;
}
$t24 = microtime(true);

/* ------------------------------ */

$t30 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr3) == 0;
}
$t31 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr3);
}
$t32 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr3 == [];
}
$t33 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr3;
}
$t34 = microtime(true);

/* ------------------------------ */

$t40 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr4) == 0;
}
$t41 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr4);
}
$t42 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr4 == [];
}
$t43 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr4;
}
$t44 = microtime(true);

/* ----------------------------------- */

$t50 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr5) == 0;
}
$t51 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr5);
}
$t52 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr5 == [];
}
$t53 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr5;
}
$t54 = microtime(true);

/* ----------------------------------- */

$t60 = $t00 + $t10 + $t20 + $t30 + $t40 + $t50;
$t61 = $t01 + $t11 + $t21 + $t31 + $t41 + $t51;
$t62 = $t02 + $t12 + $t22 + $t32 + $t42 + $t52;
$t63 = $t03 + $t13 + $t23 + $t33 + $t43 + $t53;
$t64 = $t04 + $t14 + $t24 + $t34 + $t44 + $t54;

/* ----------------------------------- */

$ts0[1] = number_format(round($t01 - $t00, 6), 6);
$ts0[2] = number_format(round($t02 - $t01, 6), 6);
$ts0[3] = number_format(round($t03 - $t02, 6), 6);
$ts0[4] = number_format(round($t04 - $t03, 6), 6);

$min_idx = array_keys($ts0, min($ts0))[0];
foreach ($ts0 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts0[$idx] = "   $val   ";
    } else {
        $ts0[$idx] = "/* $val */";
    }

}

$ts1[1] = number_format(round($t11 - $t10, 6), 6);
$ts1[2] = number_format(round($t12 - $t11, 6), 6);
$ts1[3] = number_format(round($t13 - $t12, 6), 6);
$ts1[4] = number_format(round($t14 - $t13, 6), 6);

$min_idx = array_keys($ts1, min($ts1))[0];
foreach ($ts1 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts1[$idx] = "   $val   ";
    } else {
        $ts1[$idx] = "/* $val */";
    }

}

$ts2[1] = number_format(round($t21 - $t20, 6), 6);
$ts2[2] = number_format(round($t22 - $t21, 6), 6);
$ts2[3] = number_format(round($t23 - $t22, 6), 6);
$ts2[4] = number_format(round($t24 - $t23, 6), 6);

$min_idx = array_keys($ts2, min($ts2))[0];
foreach ($ts2 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts2[$idx] = "   $val   ";
    } else {
        $ts2[$idx] = "/* $val */";
    }

}

$ts3[1] = number_format(round($t31 - $t30, 6), 6);
$ts3[2] = number_format(round($t32 - $t31, 6), 6);
$ts3[3] = number_format(round($t33 - $t32, 6), 6);
$ts3[4] = number_format(round($t34 - $t33, 6), 6);

$min_idx = array_keys($ts3, min($ts3))[0];
foreach ($ts3 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts3[$idx] = "   $val   ";
    } else {
        $ts3[$idx] = "/* $val */";
    }

}

$ts4[1] = number_format(round($t41 - $t40, 6), 6);
$ts4[2] = number_format(round($t42 - $t41, 6), 6);
$ts4[3] = number_format(round($t43 - $t42, 6), 6);
$ts4[4] = number_format(round($t44 - $t43, 6), 6);

$min_idx = array_keys($ts4, min($ts4))[0];
foreach ($ts4 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts4[$idx] = "   $val   ";
    } else {
        $ts4[$idx] = "/* $val */";
    }

}

$ts5[1] = number_format(round($t51 - $t50, 6), 6);
$ts5[2] = number_format(round($t52 - $t51, 6), 6);
$ts5[3] = number_format(round($t53 - $t52, 6), 6);
$ts5[4] = number_format(round($t54 - $t53, 6), 6);

$min_idx = array_keys($ts5, min($ts5))[0];
foreach ($ts5 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts5[$idx] = "   $val   ";
    } else {
        $ts5[$idx] = "/* $val */";
    }

}

$ts6[1] = number_format(round($t61 - $t60, 6), 6);
$ts6[2] = number_format(round($t62 - $t61, 6), 6);
$ts6[3] = number_format(round($t63 - $t62, 6), 6);
$ts6[4] = number_format(round($t64 - $t63, 6), 6);

$min_idx = array_keys($ts6, min($ts6))[0];
foreach ($ts6 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts6[$idx] = "   $val   ";
    } else {
        $ts6[$idx] = "/* $val */";
    }

}

echo "             |    count     |    empty     |     comp     |     cast     |\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Empty |";
echo $ts0[1] . '|';
echo $ts0[2] . '|';
echo $ts0[3] . '|';
echo $ts0[4] . "|\n";

echo "     Uniform |";
echo $ts1[1] . '|';
echo $ts1[2] . '|';
echo $ts1[3] . '|';
echo $ts1[4] . "|\n";

echo "     Integer |";
echo $ts2[1] . '|';
echo $ts2[2] . '|';
echo $ts2[3] . '|';
echo $ts2[4] . "|\n";

echo "      String |";
echo $ts3[1] . '|';
echo $ts3[2] . '|';
echo $ts3[3] . '|';
echo $ts3[4] . "|\n";

echo "       Mixed |";
echo $ts4[1] . '|';
echo $ts4[2] . '|';
echo $ts4[3] . '|';
echo $ts4[4] . "|\n";

echo " Associative |";
echo $ts5[1] . '|';
echo $ts5[2] . '|';
echo $ts5[3] . '|';
echo $ts5[4] . "|\n";

echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Total |";
echo $ts6[1] . '|';
echo $ts6[2] . '|';
echo $ts6[3] . '|';
echo $ts6[4] . "|\n";

Good benchmark, but you forgot sizeof which is [not?] alias of empty... stackoverflow.com/a/51986794/1429432
FYI: When I ran this benchmark using PHP 7.4, I got different results that indicated that comparison was the fastest.
You should really be using === instead of ==.
k
kenorb

If you'd like to exclude the false or empty rows (such as 0 => ''), where using empty() will fail, you can try:

if (array_filter($playerlist) == []) {
  // Array is empty!
}

array_filter(): If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

If you'd like to remove all NULL, FALSE and empty strings (''), but leave zero values (0), you can use strlen as a callback, e.g.:

$is_empty = array_filter($playerlist, 'strlen') == [];

This is the correct answer to a different question. Using array filter will destroy existing elements with falsey values. This is not what the OP is asking for.
T
Tim Ogilvy

If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:

if ($variableToTest === array()) {
    echo 'this is explicitly an empty array!';
}

R
Rob

Why has no one said this answer:

$array = [];

if($array == []) {
    // array is empty
}

Your statement is not correct. Someone DID say this answer -- Tim Ogilvy -- a year earlier. Using square braces instead of array() is the same thing.
While under the hood it is the same answer... technically. I used the square brackets instead of the outdated array function.
If you use this approch, you should also use === instead of ==, since it is faster.
@Minding: Not only because it's faster, but because it's more correct.
A
Arun A S

if you are to check the array content you may use:

$arr = array();

if(!empty($arr)){
  echo "not empty";
}
else 
{
  echo "empty";
}

see here: http://codepad.org/EORE4k7v


As shown by Cobby in 2012, it is unnecessary to call a function to check if a declared array is empty or not.
@mickmackusa I don't agree with you here. Going by that logic we could disband empty(), since empty checks whether a variable is set and whether the value is a falsey or not. Some people would rather create the (barely noticeable) overhead for readability.
If you prefer a declarative coding style, use empty(). My point is that it is not necessary.
z
zloctb
is_array($detect) && empty($detect);

is_array


These are unnecessary checks. The OP is calling explode() -- it returns array-type data. Checking empty() is an unneeded function call. As stated by Cobby in 2012, if($detect) is all that is required. This solution should not be implemented for this task or others. You might argue that you are covering situations beyond this question's scope, well, there is never a need to call empty() AFTER is_array() because if the variable is not "set", then is_array() will generate "Notice: Undefined variable", if isset() then empty() is overkill, just use Cobby's answer.
@mickmackusa what if the variable is set (to an empty array)? Maybe you want to check whether the data you are going to evaluate is even an array and then you want to check whether it's empty or not.
@Itry again, if you want to check if a declared variable is an array and is non-empty, then this is all that is required: if (is_array($detect) && $detect) If you want to force a variable to be an array, then you can cast it as an array (which will leave an array as it is, convert an object's first level to an array, and convert any scalar values into a single-element array containing the value) $detect = (array)$detect; if ($detect)
Equivalent to $detect === [], see Tim's above
P
PJately

In my opinion the simplest way for an indexed array would be simply:

    if ($array) {
      //Array is not empty...  
    }

An 'if' condition on the array would evaluate to true if the array is not empty and false if the array is empty. This is not applicable to associative arrays.


Cobby effectively stated this technique back in 2012. His answer currently has 133 upvotes.
This is not "simplest" as a matter of opinion -- it is simplest because there is no syntax that can be more concise and this has no function-call overhead. There is ABSOLUTELY NO DIFFERENCE to accessing an array with indexed keys versus associative keys. This answer is misleading researchers. This answer is redundant, then incorect. 3v4l.org/DSLha
D
David Spector

I use this code

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.


As shown by Cobby in 2012, it is unnecessary to call a function to check if a declared array is empty or not.
@mickmackusa I don't agree with you here. Going by that logic we could disband empty(), since empty checks whether a variable is set and whether the value is a falsey or not. Some people would rather create the (barely noticeable) overhead for readability
If you prefer a declarative coding style, use count(). My point is that it is not necessary.
r
reformed

You can use array_filter() which works great for all situations:

$ray_state = array_filter($myarray);

if (empty($ray_state)) {
    echo 'array is empty';
} else {
    echo 'array is not empty';
}

This answer is employing unnecessary checks. First of all, the OP is not interested in filtering any falsey values from the array before checking its emptiness -- so you have deviated from the posted question. Second, as shown by Cobby in 2012, it is unnecessary to call a function to check if a declared array is empty or not.
@mickmackusa I don't agree with you here. Going by that logic we could disband empty(), since empty checks whether a variable is set and whether the value is a falsey or not. Some people would rather create the (barely noticeable) overhead for readability
If you prefer a declarative coding style, use empty(). My point is that it is not necessary.
m
mickmackusa

Making the most appropriate decision requires knowing the quality of your data and what processes are to follow.

If you are going to disqualify/disregard/remove this row, then the earliest point of filtration should be in the mysql query.

WHERE players IS NOT NULL

WHERE players != ''

WHERE COALESCE(players, '') != ''

WHERE players IS NOT NULL AND players != ''

...it kind of depends on your store data and there will be other ways, I'll stop here.

If you aren't 100% sure if the column will exist in the result set, then you should check that the column is declared. This will mean calling array_key_exists(), isset(), or empty() on the column. I am not going to bother delineating the differences here (there are other SO pages for that breakdown, here's a start: 1, 2, 3). That said, if you aren't in total control of the result set, then maybe you have over-indulged application "flexibility" and should rethink if the trouble of potentially accessing non-existent column data is worth it. Effectively, I am saying that you should never need to check if a column is declared -- ergo you should never need empty() for this task. If anyone is arguing that empty() is more appropriate, then they are pushing their own personal opinion about expressiveness of scripting. If you find the condition in #5 below to be ambiguous, add an inline comment to your code -- but I wouldn't. The bottom line is that there is no programmatical advantage to making the function call. Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.

Here is a Demo using strlen(). This will indicated whether or not the string will create meaningful array elements if exploded.

I think it is important to mention that by unconditionally exploding, you are GUARANTEED to generate a non-empty array. Here's proof: Demo In other words, checking if the array is empty is completely useless -- it will be non-empty every time. If your string will NOT POSSIBLY contain a zero value (because, say, this is a csv consisting of ids which start from 1 and only increment), then if ($gamerow['players']) { is all you need -- end of story. ...but wait, what are you doing after determining the emptiness of this value? If you have something down-script that is expecting $playerlist, but you are conditionally declaring that variable, then you risk using the previous row's value or again generating Notices. So do you need to unconditionally declare $playerlist as something? If there are no truthy values in the string, does your application benefit from declaring an empty array? Chances are, the answer is yes. In this case, you can ensure that the variable is array-type by falling back to an empty array -- this way it won't matter if you feed that variable into a loop. The following conditional declarations are all equivalent.

if ($gamerow['players']) { $playerlist = explode(',', $gamerow['players']); } else { $playerlist = []; }

$playerlist = $gamerow['players'] ? explode(',', $gamerow['players']) : [];

Why have I gone to such length to explain this very basic task?

I have whistleblown nearly every answer on this page and this answer is likely to draw revenge votes (this happens often to whistleblowers who defend this site -- if an answer has downvotes and no comments, always be skeptical). I think it is important that Stackoverflow is a trusted resource that doesn't poison researchers with misinformation and suboptimal techniques. This is how I show how much I care about upcoming developers so that they learn the how and the why instead of just spoon-feeding a generation of copy-paste programmers. I frequently use old pages to close new duplicate pages -- this is the responsibility of veteran volunteers who know how to quickly find duplicates. I cannot bring myself to use an old page with bad/false/suboptimal/misleading information as a reference because then I am actively doing a disservice to a new researcher.


@ptr it is here.
D
Dan McGrath
empty($gamerow['players'])

some times you couldn't know element array key value $matches = preg_grep ( "/^$text (\w+)/i" , $array ) ; to check it out I use if ( count ( $matches ) > 0 )
It is assumed that the column exists in the result set, so empty() is doing too much work.
@Salem, I used to do the same thing (i.e. 'count') until I converted to PHP 7.2 .x . In spite of the "rule" that minor versions should not implement backward-breaking changes, this version of php throws a warning when "count($myArray)" is done on an empty array. That causes issues (at least in my code, & I know that some frameworks will "upgrade" it to an Exception). So be aware of this "gotcha" from php. Now, I have to cast my arrays ( (array)$myArray even though it is already defined as an array. Weird & dumb, IMO.
A
Anas Red

I think the best way to determine if the array is empty or not is to use count() like so:

if(count($array)) {
    return 'anything true goes here';
}else {
    return 'anything false'; 
}

The count() call can be removed entirely -- see Cobby's answer.
c
commadelimited
 $gamerow = mysql_fetch_array($gameresult);

if (!empty(($gamerow['players'])) {
   $playerlist = explode(",", $gamerow['players']);
}else{
 
  // do stuff if array is empty
}

R
Robbie KN

I won't repeat what has already been said here, just tested and the more efficient way on PHP-7.3 is !empty($myARR) or isset($myARR[0]), both shows same speed. Anything else is pretty slower, including array_key_exists($myARR[0]) and just comparing $myARR !== Array() | $myARR !== []. So, I prefer empty(), simple and fast.


A
Ankur prajapati
$status = "";

$new_array = array();

if(!empty($new_array)){
  $status = "1";   // not a blank array
}
else{
  $status = "0";   // blank array
}

r
rabudde

Many options have been discussed already to check if an array is empty or does not contains a value, as there are

if ($playerlist) {}

if (!empty($playerlist)) {}

if (count($playerlist) > 0) {}

All have their pros and cons.

But there is another option, that might be feasable if you are sure, that your array has numeric keys only, starting from zero (i.e. this happens if you explode() a string):

if (isset($playerlist[0])) {
  // do something
}

This is even a bit faster than the other solutions.


H
Hassan Qasim

You can use the following php functions to check whether an array is empty or not

Using empty() function

$variable = array();
    if(empty($variable)){
    echo("The array is empty.");
    }

OUTPUT: The array is empty

Using sizeof() function

$variable = array();
$arraysize = sizeof($variable);
echo("The size of the array is $arraysize. \n");
if(sizeof($variable) == 0)
echo("The array is empty.");

OUTPUT:

The size of the array is 0.

The array is empty.


J
Juan Carlos Constantine

array_filter recursive and count

function array_filter_recursive(array $arr) 
  { 
    array_walk($arr,function(&$item){if (is_array($item))  { $item = array_filter_recursive($item);}});
    return array_filter($arr); 
  } 
   
  function is_empty_array(array $arr):bool{
    return count(array_filter_recursive($arr)) == 0;
  }

test

$c=['b'=>2,'c'=>3];
$a=[];
$b=[[]];
$d=['a'=>[]];
$e=['a'=>[],[]];
$f=['a'=>[[],[],[]],[]];
$g=[[[],[[],[[],[[],[]]]]],[]];
$i=[[[],[[],[[],[[],['s'=>1]]]]],[]];
var_dump(is_empty_array($c));//false
var_dump(is_empty_array($a));//true
var_dump(is_empty_array($b));//true
var_dump(is_empty_array($d));//true
var_dump(is_empty_array($e));//true
var_dump(is_empty_array($f));//true
var_dump(is_empty_array($g));//true
var_dump(is_empty_array($i));//false

It amazes me that an answer on this question has been accepted for over a decade and it still gets new answers.
S
Suraj Kumar

I have solved this issue with following code.

$catArray=array();                          

$catIds=explode(',',$member['cat_id']);
if(!empty($catIds[0])){
foreach($catIds as $cat_id){
$catDetail=$this->Front_Category->get_category_detail($cat_id);
$catArray[]=$catDetail['allData']['cat_title'];
}
echo implode(',',$catArray);
}

Welcome to Stack Overflow! Thank you for the code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by describing why this is a good solution to the problem, and would make it more useful to future readers with other similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
M
Madhu Nair

This seems working for all cases

if(!empty(sizeof($array)))

This has too much overhead. This solution should not be implemented by any developer for any reason.
@mickmackusa Great point, but how does a novice learn to identify which operations consitute too much overhead? What's the giveaway, or what is the face value criteria for too much overhead without running performance tests?
@ptr there is a "cost" to every function call. If a task can be completed without a function call, it will outperform a technique that uses a function call.
@ptr I have posted a comprehensive answer for this question. I hope it clears up any concerns you have about this particular page.
@mickmackusa Did you mean to include a link to another post?