0
<?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?

mcan
  • 1,914
  • 3
  • 32
  • 53
  • 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 '13 at 20:25
  • @aynber but then i cannot exlude javascript functions with .js extention. – mcan Aug 15 '13 at 20:28

3 Answers3

5
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.');
      }
   } 
});
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

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>
Katana314
  • 8,429
  • 2
  • 28
  • 36
-1

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.
Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32