Question

How to Check if an Array Is Empty in PHP

phparraysis-empty

Question

I have a players field that will either be empty, contain a comma-separated list of values, or contain a single value. What is the easiest way to check whether it is empty in PHP?

I assume I can check this as soon as I fetch the $gameresult row into $gamerow. In this case, it would probably be more efficient to avoid calling explode() when players is empty. Also, for comparison, how would I check whether an array itself is empty?

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

Short Answer

By the end of this page, you will understand how to check whether a value or an array is empty in PHP, when to check before using explode(), and which PHP functions are best for strings versus arrays.

Concept

In PHP, checking whether something is "empty" depends on what kind of data you have.

In this question, there are really two separate checks:

  1. Is the players string empty before calling explode()?
  2. Is the resulting array empty after calling explode()?

These are not the same thing.

Checking an empty string

If players comes from the database as an empty string like "", you can check it before splitting:

if ($gamerow['players'] === '') {
    // no players
}

This is often the best option if you want to skip unnecessary work.

Checking an empty array

If you already have an array, PHP provides simple ways to test whether it has any elements:

if (empty($playerlist)) {
    // array has no elements
}

or

if (count($playerlist) === 0) {
    // array has no elements
}

Why this matters

In real programs, you often receive data from forms, databases, APIs, or files. Sometimes a value is missing, blank, or contains no usable items. Knowing whether to check the raw input or the processed array helps you write code that is:

  • easier to read
  • more efficient
  • less error-prone
  • safer when data is missing or malformed

Important detail about explode()

A beginner trap is assuming that exploding an empty string gives an empty array. In PHP:

explode(',', '')

returns:

['']

That means the array is not empty, even though the original string had no useful content. This is why checking the string before calling explode() is often the better choice.

Mental Model

Think of explode() like cutting a loaf of bread into slices.

  • If you have a real loaf like "Alice,Bob,Charlie", cutting it at commas gives several pieces.
  • If you have just one name like "Alice", cutting still gives one piece.
  • If you have an empty string like "", PHP still hands you one "piece" containing nothing: [''].

So if you want to know whether there is any bread at all, check before slicing.

For arrays, imagine a box:

  • an empty array is a box with nothing inside
  • a non-empty array has at least one item inside
  • [''] is still not an empty box; it contains one empty string

That difference is the key idea.

Take Quiz

Syntax and Examples

Core syntax

Check whether a string is empty

if ($gamerow['players'] === '') {
    echo 'No players';
}

Check whether an array is empty

if (empty($playerlist)) {
    echo 'Array is empty';
}

Check array length explicitly

if (count($playerlist) === 0) {
    echo 'Array is empty';
}

Example: check before explode()

$gamerow = mysql_fetch_array($gameresult);

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

This is useful because:

  • you avoid splitting an empty string
  • you get a truly empty array when there are no players
  • later code can safely treat $playerlist as an array

Example: trimming spaces

Sometimes database values may contain spaces:

$gamerow['players'] = 'Alice, Bob, Charlie';
$playerlist = explode(',', $gamerow['players']);

This creates:

['Alice', ' Bob', ' Charlie']

Notice the extra spaces. A better version is:

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

Now the result is cleaner.

Example: already have an array

$playerlist = ['Alice', 'Bob'];

if (!empty($playerlist)) {
    echo 'There are players in the list.';
}

Example: surprising explode() result

$playerlist = explode(',', '');
var_dump($playerlist);

Output:

array(1) {
  [0]=>
  string(0) ""
}

So the array is not empty, even though the original string was.

Step by Step Execution

Trace example

$players = '';

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

var_dump($playerlist);

What happens step by step

1. $players is assigned an empty string

$players = '';

At this point, there is no player data.

2. trim($players) is checked

if (trim($players) === '')
  • trim('') is still ''
  • the condition is true

3. An empty array is assigned

$playerlist = [];

Now $playerlist contains zero elements.

4. var_dump($playerlist) displays the result

array(0) {
}

That is a truly empty array.

Compare with exploding first

$players = '';
$playerlist = explode(',', $players);
var_dump($playerlist);

Step by step:

  1. $players is ''
  2. explode(',', '') runs
  3. PHP returns an array with one empty string element

Result:

array(1) {
  [0]=>
  string(0) ""
}

That is why checking first is usually the cleaner approach.

Real World Use Cases

Common places this comes up

Database fields

A column may store:

  • an empty string
  • one value
  • a comma-separated list

You often need to detect whether there is any real content before processing it.

Form input

A user may submit an optional field like:

Alice,Bob,Charlie

or leave it blank. Your code needs to handle both cases correctly.

Import scripts

CSV or text imports often contain blank values. Before splitting and processing them, you should check whether the source field is empty.

API data cleanup

An API might return a string of tags, roles, or IDs. If the field is blank, you may want an empty array instead of [''].

Filtering pipelines

Later code may loop over players, count them, or validate them. Starting with a proper empty array avoids bugs in those later steps.

Take Quiz

Real Codebase Usage

How developers commonly handle this

Guard clause before processing

A guard clause stops work early if the data is missing.

$players = trim($gamerow['players']);

if ($players === '') {
    $playerlist = [];
    return;
}

$playerlist = array_map('trim', explode(',', $players));

This keeps the main logic clean.

Normalize data into a consistent shape

Real codebases often convert different inputs into one standard format.

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

Now later code can always assume $playerlist is an array.

Validation before looping

if (!empty($playerlist)) {
    foreach ($playerlist as $player) {
        echo $player;
    }
}

Removing useless empty values

Sometimes data contains extra commas:

$players = 'Alice,Bob,,Charlie';
$playerlist = array_filter(array_map('trim', explode(',', $players)), fn($p) => $p !== '');

This removes blank entries.

Prefer modern database APIs

The example uses mysql_fetch_array(), which belongs to the old mysql_* extension. In modern PHP code, developers use:

  • mysqli
  • PDO

The emptiness-checking concept is the same either way.

Common Mistakes

1. Assuming explode('', ...) gives an empty array

Broken expectation:

$playerlist = explode(',', '');
if (empty($playerlist)) {
    echo 'No players';
}

Why this is a problem:

  • explode(',', '') returns ['']
  • the array is not empty

Better:

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

2. Using empty() when 0 might be valid

$value = '0';
if (empty($value)) {
    echo 'Empty';
}

empty('0') is true in PHP. That can be surprising.

If 0 is a valid value, use a stricter check:

if ($value === '') {
    echo 'Truly empty string';
}

3. Forgetting to trim whitespace

Broken code:

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

If the value is ' ', this check fails even though there is no useful content.

Better:

if (trim($gamerow['players']) === '') {
    $playerlist = [];
}

4. Not handling extra commas

$players = 'Alice,Bob,,';
$playerlist = explode(',', $players);

Result includes empty entries.

Better:

$playerlist = array_filter(array_map('trim', explode(',', $players)), fn($p) => $p !== '');

5. Mixing up string checks and array checks

These check different things:

empty($gamerow['players']); // checks the original value
empty($playerlist);         // checks the array variable

Choose the one that matches your actual goal.

Comparisons

String check vs array check

What you are checkingRecommended approachNotes
Raw database field is blank$players === '' or trim($players) === ''Best before explode()
Array has no elementsempty($array)Simple and readable
Array has exactly zero itemscount($array) === 0More explicit

empty() vs count()

MethodExampleGood forWatch out for
empty($array)if (empty($playerlist))Quick emptiness checksempty() also treats some non-array values as empty
count($array) === 0if (count($playerlist) === 0)When you specifically care about number of elementsOnly use when you know it is an array or countable

=== '' vs empty() for strings

CheckExampleBehavior
Strict empty string$players === ''Only true for an actual empty string
Trimmed empty stringtrim($players) === ''Also catches strings of spaces
empty($players)empty($players)Treats '', '0', 0, null, and false as empty

Best choice in this scenario

For a comma-separated players field:

  1. check the string first
  2. only call explode() if it contains content
  3. produce [] when there are no players

That leads to clearer and safer code.

Take Quiz

Cheat Sheet

Quick reference

Check if a string from the database is empty

if ($players === '')

Check if a string is empty or only spaces

if (trim($players) === '')

Check if an array is empty

if (empty($playerlist))

Check array length explicitly

if (count($playerlist) === 0)

Safe pattern for comma-separated values

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

Remove blank items after splitting

$playerlist = array_filter(array_map('trim', explode(',', $players)), fn($p) => $p !== '');

Important edge case

explode(',', '') // returns ['']

Not an empty array.

Rule of thumb

  • Check the string before explode()
  • Check the array with empty() or count() after it exists

FAQ

How do I check if an array is empty in PHP?

Use either of these:

empty($array)

or

count($array) === 0

Should I check before or after explode() in PHP?

Usually before. If the source string is empty, checking first lets you return [] instead of getting [''].

Does explode(',', '') return an empty array?

No. It returns an array containing one empty string:

['']

Is empty() safe for strings in PHP?

It is useful, but be careful: empty('0') is true. If '0' is a valid value, use === '' instead.

What is the best way to handle comma-separated values with spaces?

Use array_map('trim', ...) after splitting:

$playerlist = array_map('trim', explode(',', $players));

How can I remove empty items after splitting?

Use array_filter():

$playerlist = array_filter(array_map('trim', explode(',', $players)), fn($p) => $p !== '');

Is mysql_fetch_array() still recommended?

No. The old mysql_* functions are deprecated and removed in modern PHP. Use mysqli or PDO in new code.

Take Quiz

Mini Project

Description

Build a small PHP script that reads a comma-separated players value, converts it into a clean array, and handles empty input correctly. This demonstrates the difference between an empty string, an empty array, and an array that contains blank values.

Goal

Create a player list parser that returns a clean array of player names and safely handles empty or messy input.

Requirements

  • Read a players string variable that may be empty, contain one name, or contain multiple comma-separated names.
  • If the string is empty or only spaces, return an empty array.
  • Split non-empty strings into an array.
  • Trim whitespace around each player name.
  • Remove blank entries caused by extra commas.
Take Quiz

Keep learning

Related questions

View more