I have two arrays of fruits and corresponding prices. I want to search for a fruit in the fruits array and use the found index to get the price using the prices array.
@echo off
setlocal enabledelayedexpansion
set "fruits[0]=6"
set "fruits[1]=Apple"
set "fruits[2]=Banana"
set "fruits[3]=Orange"
set "fruits[4]=Grapes"
set "fruits[5]=Mango"
set "fruits[6]=Pineapple"
set "prices[0]=6"
set "prices[1]=10"
set "prices[2]=30"
set "prices[3]=25"
set "prices[4]=15"
set "prices[5]=12"
set "prices[6]=16"
REM Example 1 works
call :SearchInArray "fruits" "Orange"
set /a i=result
echo Result found index: !i!
echo Fruit found: !fruits[%i%]!
echo Price: !prices[%i%]!
echo.
REM Example 2 works
call :SearchInArray "fruits" "Grapes"
set /a i=result
echo Result found index: !i!
echo Fruit found: !fruits[%i%]!
echo Price: !prices[%i%]!
echo.
REM Example 3 using a for loop does not!
set "searchValues=Orange Grapes"
for %%s in (%searchValues%) do (
call :SearchInArray "fruits" "%%s"
set /a i=!result!
echo Result found index: !i!
echo How to display here the price of the found fruit using the result found index?
)
exit /b
:SearchInArray
set "array=%~1"
set "searchString=%~2"
set "arrayLength=!%array%[0]!"
REM echo array=%array%
REM echo searchString=%searchString%
REM echo arrayLength=%arrayLength%
set "index=-1"
REM Loop through the array elements
for /L %%i in (1, 1, %arrayLength%) do (
REM echo !%array%[%%i]!
if "!%array%[%%i]!" == "%searchString%" (
set "index=%%i"
goto :ExitLoop
)
)
:ExitLoop
REM Output the index of the string in the array
REM echo Index of "%searchString%" in the array: %index%
set "result=%index%"
exit /b
Output:
Example 1
Result found index: 3
Fruit found: Orange
Price: 25
Example 2
Result found index: 4
Fruit found: Grapes
Price: 15
Example 3
Result found index: 3
How to display the price of the found fruit using the result found index?
Result found index: 4
How to display the price of the found fruit using the result found index?
In first two examples it works as expected, but if I want to do it in a for loop using an string searchValues
containing search strings it does find it but I struggle accessing the prices array using the found index. None works:
echo Price method 1: prices[!i!]
echo Price method 2: %prices[!i!]%
echo Price method 3: !prices[!i!]!
echo Price method 4: !!prices[!i!]!
echo Price method 5: %prices[%i%]%
echo Price method 6: !prices[%i%]!
echo Price method 7: !!prices[%i%]!
Output:
Price:
Price: i
Price: i
Price: i
Price: 15
Price: 15
Price:
Price: i
Price: i
Price: i
Price: 15
Price: 15
It should be 15 for the first fruit Orange and 25 for the second fruit Grapes.