@sanfordwhiteman goes into great detail on the troubling issues of foreach statements and links in Velocity here on his blog. I would encourage you to start there and see how much overlap there is with your use case and how he recommends approaching a solve. I'll also 100% defer to him on a more elegant solution / blob of VTL code if one exists!
We had a similar conundrum of needing to pass over a SFDC custom object that had a variable number of links stored in it to output properly tracked URLs. That was the foreach loop wasn't actually creating unique variables for every link it encountered in the object. What worked for us was to combine the foreach statement with an evaluate statement to create unique variables as the script encountered them.
Something a little like this:
#foreach ( $question in $arraytest)
#evaluate( "${esc.h}set( ${esc.d}finalurl_${foreach.count} = ${esc.d}arraytest[$i].question_url )" )
#evaluate( "${esc.h}set( ${esc.d}finaltitle_${foreach.count} = ${esc.d}arraytest[$i].question_title )" )
#set ( $i = ${foreach.count} )
#end
Why this worked for us: we had a maximum number of potential links that could ever exist, and so we knew how many corresponding variable sets the foreach and evaluate statements produced (in our case, 5). We simply combined that with conditional if statements to render the link, should the variable exist because of the foreach.
Something like this:
#if( $finalurl_1 )
<p><a href="https://${finalurl_1}">$finaltitle_1</a></p>
#end
#if( $finalurl_2 )
<p><a href="https://${finalurl_2}">$finaltitle_2</a></p>
#end
#if( $finalurl_3 )
<p><a href="https://${finalurl_3}">$finaltitle_3</a></p>
#end
#if( $finalurl_4 )
<p><a href="https://${finalurl_4}">$finaltitle_4</a></p>
#end
#if( $finalurl_5 )
<p><a href="https://${finalurl_5}">$finaltitle_5</a></p>
#end
Again, there may be a more elegant way of producing the same result and I will happily defer to someone more experienced with VTL like @sanfordwhiteman -- but in essence, you have to have unique variables for the links.
Hope this helps!