Loop Support in AMPscript

My hacky stupid workaround for While loops in AMPscript:

%%[ FOR @i=1 to 2 DO
      /*Execute your code here*/
      IF NOT @condition THEN
        @i = Subtract(@i, 1)
      ENDIF
    NEXT @i ]%%

This loop will keep executing until the condition is met.


I have put some time into this and in the resources it only lists FOR/TO(DOWNTO) as a viable looping option.

I have attempted FOR/IN and received a definitive syntax error that FOR requires to be followed by TO or DOWNTO - which means the functionality is definitely not there.

I then investigated using WHILE, which has no documentation at all and provided no errors when used - BUT it did not actually do what it was supposed to do. After looking through the code and using AMPScript editors to check syntax, etc. I have found out that both DO and WHILE are not recognized as commands. This means that there is no inherit capability to achieve these.

Basically what it comes down to is that the only available inherit looping function in AMPScript is FOR/TO(DOWNTO) and without tremendous 'hacking' of the inherit functionality (not even sure THAT is possible), of which I have not yet found a good use case, it is not possible to use the other loop types directly in AMPScript. You would need to use SSJS to achieve these.

SFMC support (helpful as always) directed me to the documentation resource listed above and told me those are the only available commands/functions.


Based on ncv solution:

%%[ 
        SET @x = 2
        FOR @i=1 to @x DO
           /*Execute your code here*/
           IF NOT @condition THEN
             @x = add(@x, 1)
           ENDIF
        NEXT @i 
]%%