Skip to main content

How to Count Elements in an Array in Batch Script

Knowing the size of an array is essential for building loops, calculating averages, or verifying if a data import was successful. In Batch, there is no native count() function for variables. To find the number of elements, you must iterate through the defined variable names and increment a counter.

In this guide, we will demonstrate two ways to count elements: one for "indexed" arrays and one for "dynamic" collections.

Method 1: The Indexed Counter (Best for Loops)

If your array follows a standard index pattern (e.g., ARR_1, ARR_2), you can find the count by looking for the first "Undefined" variable.

note

This method requires your array indices to be contiguous (no gaps). If ARR_2 is missing but ARR_3 exists, the count will stop at 1. For sparse or non-sequential collections, use Method 2.

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: Setup an example array
set "ARR_1=Apple"
set "ARR_2=Orange"
set "ARR_3=Banana"
set "ARR_4=Grapes"

set "count=0"

echo Analyzing indexed array...

:count_loop
set /a "next=count + 1"
if defined ARR_!next! (
set "count=!next!"
goto :count_loop
)

echo.
echo ==========================================
echo ARRAY SIZE: !count!
echo ==========================================

endlocal
pause

Method 2: The "Pattern" Count (Best for Dynamic Lists)

If you have a collection of variables with a common prefix (like KV_) and you don't know if the numbers are sequential, you can use the set command combined with find /c.

tip

This method counts all variables matching a prefix regardless of their naming pattern, making it ideal for dictionary-style collections where keys are not numeric indices.

Implementation Script

@echo off
setlocal

:: Create some variables with a 'User_' prefix
set "User_John=Active"
set "User_Alice=Idle"
set "User_Bob=Active"
set "User_Eve=Banned"

echo Counting all variables starting with 'User_'...

:: 'set User_' lists all matching variables
:: This method counts matches by iterating through the list directly
set "total=0"
for /f "delims=" %%A in ('set User_ 2^>nul') do set /a "total+=1"

echo Total Users: %total%

endlocal
pause

Why Count Array Elements?

  1. Loop Boundaries: Ensuring your FOR /L loop doesn't try to access items that don't exist.
  2. Validation: Verifying that a file search found exactly the number of files you expected.
  3. Reporting: Generating a summary ("Processed 50 records") at the end of a bulk automation task.

Important Considerations

warning

If you use a generic prefix like A_, the set A_ command may accidentally match system or script variables that are not part of your array. Always use a specific, descriptive prefix like ARR_, DAT_, or User_ to avoid inflated counts from environment collisions.

  1. Fragmentation: Method 1 assumes your array is "Contiguous" (no gaps). If you have ARR_1 and ARR_3 but ARR_2 is missing, the loop will stop at 1 and report the count as 1.
  2. Environment Collisions: If you use a generic prefix like A_, you might accidentally count variables that aren't part of your array. Always be specific, like DAT_ or ARR_.
  3. Case Sensitivity: Variable names in set commands are case-insensitive. set a_ will list A_first and a_second alike.

Best Practices

  1. Track as You Go: The most efficient way to maintain a count is to increment a total variable every time you add an item to the array, rather than counting them all at the end.
  2. Initialize Before Counting: Before building a new array in Method 2, clear any leftover variables from a previous run by looping through and unsetting each one. This prevents stale data from inflating your count.

Conclusion

Counting array elements is a foundational monitoring task that provides necessary context for your loops and reports. Whether you use a sequential "Defined" check or a pattern-based log count, knowing the exact size of your data set ensures your automation is accurate and reliable. By mastering these counting techniques, you turn a collection of variables into a structured, manageable inventory.