Link to home
Create AccountLog in
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

Avatar of Kyle Hamilton
Kyle Hamilton
Flag of United States of America image

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
Avatar of Kyle Hamilton
Kyle Hamilton
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of meno19
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?
a for loop will increment. A foreach just applies the same code to each item in the array
Avatar of meno19

ASKER

oh right, alright ill give that a shoot and see if setting the variable names like that would work. It should.
Avatar of meno19

ASKER

Nevermind I figured out my other question. Gonna try this next.
Avatar of meno19

ASKER

BRILLIANT. Worked like a charm 5 BILLION POINTS. Thank you for all the help.
That's great. For the 5 billion points just "Accept" an answer. :))

Koza.
Avatar of meno19

ASKER

LOL my Bad your all set now.