Echo batch file arrays using a variable for the index?

arrays, batch-file, echo

Solution

SET x=1
SET myVar[%x%]=happy

call echo %%myvar[%x%]%%
set myvar[%x%]
for /f "tokens=2* delims==" %%v in ('set myvar[%x%]')  do @echo %%v
setlocal enableDelayedExpansion
echo !myvar[%x%]!
endlocal

I would recommend you to use

setlocal enableDelayedExpansion
echo !myvar[%x%]!
endlocal

as it is a best performing way

Problem

If I have a batch file and I am setting arrays with an index that is a variable ``` @echo off SET x=1 SET myVar[%x%]=happy ``` How do I echo that to get "happy" ? I've tried ``` ECHO %myVar[%x%]% ECHO %%myVar[%x%]%% ECHO myVar[%x%] ``` But none of them work. It works fine if I use the actual number for the index ``` ECHO %myVar[1]% ``` But not if the index number is also a variable

Original source

Related problems