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']);
1/2/2017 7:16:32 PM

Accepted Answer

If you just need to check if there are ANY elements in the array

if (empty($playerlist)) {
     // 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 (empty($value)) {
if (empty($playerlist)) {
   //empty array
5/18/2016 5:02:20 PM

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

$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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow