How to check whether an array is empty using PHP
Determining if an array contains data is a fundamental operation, yet the choice of operator can significantly impact performance and readability depending on your specific use case. You might encounter scenarios where you need to distinguish between an array that has been explicitly set to null, one that was never populated, and one that legitimately holds zero items.
In the context of parsing game data, such as the $gameresult example provided, efficiency matters. If you are fetching a row from a database and expecting a comma-separated list of players, you often want to avoid running an explode() function on a string if it yields no results. The goal is to check the state of the array immediately after creation or during processing without unnecessary overhead.
The Universal Truth: count()
The most robust and universally understood method for checking an array's size is using the count() function combined with a strict comparison to zero. This approach works regardless of whether the variable holds a native PHP array, a result from a database query, or data parsed from a string.
$playerlist = explode(',', $gamerow['players']);
if (count($playerlist) === 0) {
// Handle empty list
}
This logic is explicit. It answers the question "how many elements are in this collection?" and returns false if the count is zero. While slightly more verbose than some alternatives, it leaves no ambiguity about what you are checking. You can also use count($playerlist) > 0 to check for existence directly, which some developers find reads more naturally as a condition.
The Shortcut: Empty Operator
For simple scenarios where you only care if the array is empty or not, the empty() built-in function is the standard choice in modern PHP development. It evaluates several conditions as "truthy" when passed an array: the array is empty, the array is null, or the array is false.
if (empty($playerlist)) {
// The array has no elements
}
The empty() operator is generally preferred for readability in standard application logic because it collapses multiple checks into a single, clear statement. It is particularly useful when you want to ensure data exists before attempting further processing, such as looping through player names or rendering a list in a view. However, keep in mind that empty() returns true if the variable is set to the string "0" or an empty string "". While this rarely causes issues with arrays (since an array cannot be the string "0"), it is important to remember that empty() checks for truthiness rather than just length.
Avoiding Premature Optimization
The source material suggests optimizing by skipping the explode() function if the input string is empty before even creating the array. While this is a valid performance consideration, it requires checking the raw string value first:
$playersRaw = $gamerow['players'] ?? ''; // Handle missing key safely
if (empty($playersRaw)) {
$playerlist = [];
} else {
$playerlist = explode(',', $playersRaw);
}
This pattern prevents the creation of an array containing a single empty string element if the source is just a comma. It ensures that $playerlist is either an empty array or an array of names. By handling the empty state at the point of parsing, you guarantee that subsequent count() or empty() checks are always performed on a valid array structure, avoiding edge cases where the variable might be null.
Best Practices for Data Safety
When dealing with external data sources like database results, it is crucial to handle cases where keys might be missing entirely. Using the null coalescing operator (??) or the traditional isset() check before accessing $gamerow['players'] prevents undefined index notices. If you proceed directly to explode() on a potentially empty string, PHP returns an array containing one element: an empty string.
// This creates [''] not []
$bad = explode(',', '');
var_dump(count($bad)); // Outputs 1
This is why checking with count() or empty() after the operation remains the safest final step. It guarantees that your logic holds regardless of whether the string was empty, null, or contained only whitespace. Always validate the resulting array before assuming it contains data to iterate over.