0

I am trying to get a dynamic variable set inside a script block with AMPScript.

Here is what I got:

FOR @i = 1 to 5 DO
    TreatAsContent( Concat( "SET @Test", @i, " = ", 'some value' ) )
NEXT @id

SET @somethingElse = @Test1

@Test1 does not exists.

How do I get a dynamic variable name created inside a loop?

Update

Here is my working solution in AMP Script (no SSJS)

%%[

SET @someValue = 'Test'
SET @anotherSample1 = 'Sample1'
SET @anotherSample2 = 'Sample2'
SET @anotherSample3 = 'Sample3'
SET @anotherSample4 = 'Sample4'
SET @anotherSample5 = 'Sample5'

FOR @i = 1 to 5 DO

    /* Create a variable Test1, Test2 ... with the value of variable @someValue */
    TreatAsContent( Concat( "%", "%[ SET @Test", @i, " = '", @someValue, "']%", "%" ) )



    /* Access a variable based on the loop integer */
    SET @var = TreatAsContent( Concat("%%=v(@anotherSample",@i,")=%%") )

    /* Create a variable AnotherSample1, AnotherSample2 ... with the value of variable @anotherSample1, anotherSample2 ... */
    TreatAsContent( Concat( "%", "%[ SET @AnotherSample", @i, " = '", @var, "']%", "%" ) )

NEXT @id

/* OUTPUT:

@Test1 = 'Test'
@Test2 = 'Test'
@Test3 = 'Test'
@Test4 = 'Test'
@Test5 = 'Test'

@AnotherSample1 = 'Sample1'
@AnotherSample2 = 'Sample2'
@AnotherSample3 = 'Sample3'
@AnotherSample4 = 'Sample4'
@AnotherSample5 = 'Sample5'

]%%
0

If your loop scope is static then you could do the following:

FOR @i = 1 to 5 DO
    IF @i==1 THEN SET @Test1 = 'some value1' ENDIF
    IF @i==2 THEN SET @Test2 = 'some value2' ENDIF
    /* ... etc */
NEXT @id
SET @somethingElse = @Test1

Your example is presumably a simplified example, so unlikely that the scope is fixed. In this case, what you are trying to do is not possible with Ampscript. Depending on your context, you could use SSJS, and JS object properties.

<script runat=server>
Platform.Load("core","1.1.5");
var myObject = {};
var myArray = ['a','b','c'];
for (var i=0; i<myArray.length; i++) {
    myObject['Test'+i] = 'some value';
}
var somethingElse = myObject.Test0;
Write(somethingElse); // Output is 'some value'
</script>

See also this documentation on using SSJS with Ampscript.

  • 1
    Thank you Josh. I have found this example were the second answer seems to have the same approach and presumably works. And yes mine is a very simplified example. salesforce.stackexchange.com/questions/31819/… – Sascha Jun 13 at 3:26
  • That approach does actually work. I tried something similar that didn't. Well, today I learned something. Nice find! – Josh de Blank Jun 13 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.