cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Foreach-construct makes it possible to iterate over variables of type collection and JSON arrays in API-responses.

 

The basic syntax looks as follows:

 

foreach ($iterable, {number_of_iterations})
statement
endforeach

 

The first parameter specifies the variable to be looped over, the second defines the number of iterations (numeric, optional).

 

Foreach with collections

In our example the user is asked to pick his favorite colors from the list of predefined ones in the variable $color$. The user's choice is then saved into a variable $color$ of datatype collection. The bot confirms user’s choice and returns colors saved in $color$ (max 3). This is achieved by iterating over a variable $color$ (max. 3 iterations) and printing the $value$ of the current color element preceded by its $index$.

 

4.png

 

Here is how it looks in WhatsApp:

 

5.png

 

Foreach with JSON Arrays

Similarly you an iterate over JSON arrays in API responses. In our example the user receives a weather forecast for the next 3 days, fetched with an API call from openweathermap.org.

The JSON Response contains an array with daily weather information for the upcoming 7 days:

 

6.png

 

 

The complete API response is saved into a variable $api$. The array with daily information is accessed by using a JSON-Path in the variable ($api.daily$) and is used as the first parameter to be iterated over in the foreach-loop. Within the loop you can directly access respective response attributes  (in our example: $temp.day$, $weather.0.description$).

 

7.png

 

This is how the dialogue looks in WhatsApp:

 

9.png

Version history
Last update:
‎02-19-2026 07:06 AM
Updated by: