dimanche 25 mars 2012
ASP: dynamic variable names
Do you like this story?
I've been programming in ASP for such a long time that sometimes I do not really value its power. Today we are going to see an extreme example: dynamic variable names. I say "extreme" because I believe that the real use of the following code might be quite rare, however in some extreme situations, we need extreme - I know I repeat myself - solutions.
We are going to use different ASP stuff: an array and the execute and eval functions. At the same time we are going to use the split function, in order to create the array.
Some assumptions
The following example starts from a precise idea. Imagine we have a variable that contains different values. Those values are separated by a semicolon. Something like:TheString = "01;02;03;04;05"We need to create a certain number of variables depending on the values contained in TheString and assign those values to different variables. In short, we need to obtain something like:
a1 = "01"
a2 = "02"
a3 = "03"
a4 = "04"
a5 = "05"At the same time, we do not know beforehand the number of variables we will need, because we don't know the number of values in TheString.
The array
The first thing we need is to create the array. To do so, we split TheString considering the semicolon as separator.<%
Dim TheArray
Dim TheString
TheString = "01;02;03;04;05"
TheArray = split(TheString, ";")Items and variables
We use a For... Next to go through every item in the array. At the same time, for the purpose of this example, we are showing the items values with response.write:
Dim i
i = 1
For each item in TheArray
response.write "<br>Item Value: " & itemexecute("a" & i & " = item")
i = i + 1
NextShow the dynamic variables
As said, we don't know how many variables we created: it depends on the number of items in the array. Anyway, we can cycle throught those variables using an approach similar to the above. The number of variables is i minus 1. We then use j for a new For... Next cycle:i = i - 1
Dim j
For j=1 to i
response.write "<br>a" & j &": " & eval("a" & j)
Next
%>Item Value: 01
Item Value: 02
Item Value: 03
Item Value: 04
Item Value: 05
a1: 01
a2: 02
a3: 03
a4: 04
a5: 05And that is all. Let me know if you've found the above information useful!

This post was written by: Franklin Manuel
Franklin Manuel is a professional blogger, web designer and front end web developer. Follow him on Twitter
Inscription à :
Publier les commentaires (Atom)


0 Responses to “ASP: dynamic variable names”
Enregistrer un commentaire