Avatar of meno19
meno19
 asked on

Append a Javascript Variable Name

This is most likely pretty simple but I am not getting it right. What I want to do is when creating a javascript variable is append a number to its name so instead of var test=5 have it be var test0 = 5. How do you append a variables name when creating it.

I am trying to append to the javascript since it is being created within a php loop.

<?php
	$sequence = 0;
		
	foreach($result_data as $test)
	{			
		?>
		<script type="text/javascript">	        					
			
			var contentString<?php echo $sequence;?> = '5';

		</script>        
		<?php
           $sequence++; 	
	}
	?>

Open in new window

JavaScriptScripting Languages

Avatar of undefined
Last Comment
meno19

8/22/2022 - Mon
Kyle Hamilton

Use a for loop instead of a foreach. Also, I'm assuming you just want one script with multiple variables? thus don't write the script tags in the loop.

<?php
      

        $count = sizeof($result_data); // result_data is an array?

        echo "<script type='text/javascript'>";
            
      for($i = 0; $i < $count; $i++)
      {                  
      echo "var contentString"  . $i . " = '5'";
        }

        echo "</script> ";
      

?>
ASKER CERTIFIED SOLUTION
Kyle Hamilton

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
meno19

ASKER
Oh I see how your doing it. You are writing out the javascript via a php echo, doing the variable name setup in PHP. I've been trying to do it in javascript.

Why use a for instead of a foreach loop?
Kyle Hamilton

a for loop will increment. A foreach just applies the same code to each item in the array
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
meno19

ASKER
oh right, alright ill give that a shoot and see if setting the variable names like that would work. It should.
Kyle Hamilton

cool.
meno19

ASKER
Nevermind I figured out my other question. Gonna try this next.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
meno19

ASKER
BRILLIANT. Worked like a charm 5 BILLION POINTS. Thank you for all the help.
Kyle Hamilton

That's great. For the 5 billion points just "Accept" an answer. :))

Koza.
meno19

ASKER
LOL my Bad your all set now.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck