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:
- Is the
playersstring empty before callingexplode()? - 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
(() === ) {
}
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.
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 = (, []);
}
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
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.
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.
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 (()) {
;
}
Comparisons
String check vs array check
| What you are checking | Recommended approach | Notes |
|---|---|---|
| Raw database field is blank | $players === '' or trim($players) === '' | Best before explode() |
| Array has no elements | empty($array) | Simple and readable |
| Array has exactly zero items | count($array) === 0 | More explicit |
empty() vs count()
| Method | Example | Good for | Watch out for |
|---|
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(, ));
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?
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
playersstring 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.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.