Solved: How to index into array with variable in batch?

Abstract: Resolve incorrect variable expansion when accessing pseudo-array elements with dynamic indices in Windows Batch scripts by enabling delayed variable expansion.

Created: 2026-08-10 by
You cannot index into arrays with variables in batch scripting using standard syntax because Windows Batch does not support native array data structures. To achieve dynamic indexing, you must use delayed variable expansion and the !variable! syntax instead of the standard %variable% syntax. This allows the script to evaluate the variable's value at execution time rather than parse time, enabling you to access specific elements stored in a pseudo-array format.

Understanding Batch Variable Expansion

The core issue stems from how the Windows Command Processor parses scripts. By default, the parser expands all <code>%var%</code> references when it reads a block of code (such as inside a for loop or an if statement), before that block actually executes. If you try to use a variable that changes within that block to index another variable, the initial value is used for the entire duration of the block, leading to incorrect results. To solve this, you need Delayed Expansion. When enabled, the system uses exclamation marks (!) instead of percent signs to expand variables. These expansions happen right before the command line is executed, ensuring that the most current value of the variable is used. This mechanism is essential for any operation involving dynamic indices, loops, or conditional logic where values change mid-script.

Enabling Delayed Expansion

Before you can use the ! syntax, you must enable it in your batch file. You can do this by adding the following command near the top of your script:
setlocal EnableDelayedExpansion
This command tells the command processor to allow delayed variable expansion for the remainder of the script. Without this line, any attempt to use !var! will result in the literal characters being printed or ignored, rather than expanding to the variable's content. It is also good practice to pair this with setlocal to ensure that environment variables created in your script do not leak into the parent environment after the script finishes.

Simulating Arrays in Batch

Since Batch lacks built-in arrays, developers typically simulate them using numbered variable names. For example, you might store items in variables named array_0, array_1, array_2, and so on. To access these dynamically, you construct a new variable name string that includes the index variable. Here is a concrete example of how to set up and access such a structure:
@echo off
setlocal EnableDelayedExpansion

:: Define pseudo-array elements
set "arr_0=Apple"
set "arr_1=Banana"
set "arr_2=Cherry"

:: Set the index variable
set /p "idx=Enter index (0-2): "

:: Access the element using delayed expansion
echo The item at index !idx! is: !arr_!idx!!
In this snippet, the final echo statement constructs the variable name arr_!idx!. Because delayed expansion is active, !idx! is evaluated first. If the user enters 1, the command processor looks for the variable arr_1 and retrieves its value, "Banana".

Using For Loops with Dynamic Indices

Dynamic indexing is most commonly encountered within for loops. Consider a scenario where you want to iterate through a list of files and process them based on their position. Standard percent expansion fails here because the loop variable changes, but the parser has already fixed the variable references.
@echo off
setlocal EnableDelayedExpansion

set "file_0=data.txt"
set "file_1=notes.txt"
set "file_2=readme.txt"

for /L %%i in (0,1,2) do (
    echo Processing file %%i: !file_%%i!
)
Notice the mix of %%i and !file_%%i!. The %%i is the loop counter and is expanded normally because it is part of the loop control structure. However, !file_%%i! uses delayed expansion to resolve the filename. The %%i inside the exclamation marks is treated as a literal character during the initial parse, but when the command runs, %%i holds its current loop value, allowing !file_0!, !file_1!, etc., to be resolved correctly. If you are working with complex directory structures, you might also find it useful to manage paths dynamically. For more information on manipulating directories relative to your current location, see How can I use Windows .bat files to create folder above current folder?.

Common Pitfalls and Best Practices

One frequent error is mixing % and ! carelessly. If you define a variable inside a block using %var%, it will retain its value from before the block started. Always use ! for variables that change within blocks. Additionally, be cautious with spaces. In Batch, spaces around the equals sign in assignments matter. set var=value is correct, while set var = value creates a variable named var (with a trailing space), which breaks indexing lookups. Another pitfall involves uninitialized variables. If your index variable points to a non-existent array element, !arr_5! will simply expand to nothing. You should implement checks to ensure the index is within valid bounds before attempting access. This prevents silent failures that can be difficult to debug in larger scripts. For related techniques on managing file operations within scripts, check out Batch File to Rename and Move File to Parent Directory. Understanding how to handle paths and filenames robustly complements the logic needed for dynamic data retrieval.

Advanced Indexing with Substrings

While numbered variables are the simplest method, you can also use substring extraction to map keys to values. This approach is less efficient for large datasets but useful for small, static mappings. However, for true dynamic indexing based on user input or loop counters, the numbered variable approach with delayed expansion remains the most reliable and performant solution in pure Batch scripting.

Frequently Asked Questions

Can I use arrays in PowerShell instead of Batch?

Yes, PowerShell supports native arrays and hash tables, making dynamic indexing much easier with standard syntax like $myArray[$index]. If you are starting a new project, consider using PowerShell over Batch for better data structure support.

Why does my variable show the old value inside a loop?

This happens because Batch expands %var% at parse time, before the loop begins. To fix this, enable delayed expansion with setlocal EnableDelayedExpansion and use !var! instead.

What if my index variable contains spaces?

Spaces in variable names or values can break the lookup. Ensure you quote your variable assignments and expansions properly. Use "!arr_!idx!!" to prevent word splitting issues during execution.

Is there a performance penalty for delayed expansion?

The performance impact is negligible for small scripts. However, for very large loops processing thousands of iterations, the overhead of parsing delayed expansions might slightly slow down execution compared to simple sequential commands.

How do I clear a simulated array?

You can clear individual elements by setting them to empty strings using set "arr_0=". There is no bulk delete command for pseudo-arrays, so you must iterate through known indices to clean them up manually.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More