php count the number of strings after exploded

php count the number of strings after exploded

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Counting Elements After Exploding a String in PHP

When you need to process a delimited string in PHP, explode() is the standard utility. However, developers often struggle when they need to know exactly how many items were split or iterate through them using 1-based indexing. Consider a scenario where $string contains 'a|b|c|d|e|f'. After running explode('|', $string), you get an array with six elements. The immediate challenge is determining the count without simply relying on the length of the resulting array, or adjusting the loop index to start at 1 instead of 0.

Using count() for Length Determination

The most direct way to determine the number of strings after exploding a delimiter is to use PHP's built-in count() function. This returns the number of elements in an array, which corresponds to the number of substrings split by the delimiter.

$string = 'a|b|c|d|e|f';
$tags = explode('|', $string);

$totalItems = count($tags); // Returns 6
echo "Total items found: " . $totalItems;

This approach is robust because it separates the counting logic from the iteration logic. If your application needs to validate that a minimum number of tags exists before processing, count() provides an immediate integer you can evaluate against thresholds. Note that if the input string contains leading or trailing delimiters (e.g., '|a|b|'), explode will create empty strings at the start or end. The count remains accurate to the number of resulting elements, even if some are empty, unless you filter those out first.

Iterating with 1-Based Indexing

The second requirement in many scenarios is to have the loop index start at 1 rather than 0. While PHP arrays are internally zero-indexed, presentation logic often demands human-readable numbering. You do not need to modify the array keys; you simply adjust the counter variable inside the loop or use a separate tracking variable.

The original code snippet attempted to use $i as both the value and the key, which is syntactically incorrect ($i > 0; does not assign a value). To fix this while maintaining 1-based indexing, you should initialize a separate counter variable:

$string = 'a|b|c|d|e|f';
$tags = explode('|', $string);

$counter = 1; // Start at 1

foreach ($tags as $key) {
    echo $counter . ' ' . $key . '</br>';
    $counter++;
}

Output:

1 a
2 b
3 c
4 d
5 e
6 f

Alternatively, if you prefer to use the loop index directly, you can calculate it dynamically. Since foreach assigns the key (which is 0-based) to $key, you can output $key + 1 whenever you need the human-readable number:

foreach ($tags as $index => $value) {
    echo ($index + 1) . ' ' . $value . '</br>';
}

Performance Considerations with Large Datasets

When dealing with massive strings containing thousands of delimiters, calling count() is an O(1) operation because it relies on the array's internal size tracker. However, if you are processing data in a stream or need to save memory by avoiding the full array creation, explode might not be the ideal first step. In such cases, using str_split() with a custom delimiter isn't directly possible without regex, which introduces overhead.

If performance is critical and you must count occurrences of a specific character or split logic without creating the full array immediately, substr_count() can help determine potential segments, though it won't handle empty segments between consecutive delimiters correctly unless combined with other logic. For standard use cases, explode followed by count() is the most readable and efficient path in PHP 7.4+.

Handling Edge Cases

A common pitfall occurs when the input string ends with the delimiter. For example, 'a|b|' explodes into three items: ['a', 'b', '']. The count will be 3. If your business logic treats empty strings as invalid tags, you must filter them before counting or iterating.

$tags = explode('|', $string);
// Filter out empty strings if they shouldn't count
$validTags = array_filter($tags, fn($item) => $item !== '');
$totalValid = count($validTags);

This ensures that your count reflects only the actual data points you intend to process. Always verify whether empty elements are significant in your specific context before deciding to filter them out.

For further reading on string manipulation best practices within the Laravel ecosystem, you might explore resources like https://laravelcompany.com which often cover advanced collection helpers that can simplify array operations once the data is loaded into a model or collection.

Our network