Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

<?php
   $heros=array("Spiderman","Batman","Superman");
?>

<script type="text/javascript">
   var heros = <?php echo $heros;?> // I don't want to do this.
   for(i=0; i<3; i++)
   {  
      if(heros[i]=='Spiderman')
      {
        alert('Hey! I am Spiderman.');
      }
   }
</script>

I want to use a php array inside javascript for loop but i don't want to reopen php tags inside <script></script> tags. How can i use php variables in javascript?

share|improve this question
2  
You're going to have to reopen the php tags, because there's no other way to make the server treat it as php. – aynber Aug 15 at 20:25
@aynber but then i cannot exlude javascript functions with .js extention. – Tahtakafa Aug 15 at 20:28

marked as duplicate by T.J. Crowder, kalley, Kate Gregory, tereško, Nirk Aug 16 at 0:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

var heros = <?php echo json_encode($heros);?> // You have to do this.

If you really don't want to open php tags inside your JS, you'll have to issue an ajax request to the server and grab the data asynchronously. Then your code would look like this (using jQuery for shortness):

$.getJSON('/url/that/responds/with/json', function(heros) {
   for(i=0; i<3; i++)
   {  
      if(heros[i]=='Spiderman')
      {
        alert('Hey! I am Spiderman.');
      }
   } 
});
share|improve this answer

In terms of direct ways, bfavaretto is correct.

If this sort of issue comes up often for you, you may consider a more generalized solution; our app has a "context" variable that contains string-indexed values manipulated several times in PHP. Then, as part of our header code, its contents are initialized to a Javascript variable. Obviously, we only use this for things we intend to expose to the client. Something like this:

<?php
include('header1.php');
$context['heroes'] = array('Spiderman', 'Batman');

...do some extra processing with this context variable...
include('header2.php');
?>

<script>
  var heroes = myApp.context.heroes;
</script>
share|improve this answer

Wrong solution:

You can echo all the javascript code in php, and then use the json encode, that's the only way you don't need to reopen the php tag in the javascript tags.

Solution:

Just use the answer already given:

var heros = <?php echo json_encode($heros);?> // You have to do this.
share|improve this answer
Why would you give a wrong answer followed by a copy of a good answer? – Herbert Aug 15 at 23:53
Because he asked if it was possible, so i showed him it is possible but it's not a good solution. – Stefan Koenen 2 days ago

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