Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am getting an array in php, and send it to smarty .tpl file.

In smarty I would like to get that array in a java script variable .

How to do this . Please help me ...

share|improve this question

5 Answers 5

simplest way is to use json:

<script type="text/javascript">
var arr = <?= json_encode($arr) ?>;
</script>

json_encode() takes you php data and converts it into json, amd in our case its exactly what we need

share|improve this answer

I think it should simple like

<?php
  $_array = array('apple','banana','durian');
  $js_array = '[' . implode(',',$_array) . ']';
?>

<script type="text/javascript">
    var iArray = <?php echo $js_array;?>;
</script>
share|improve this answer

In php file just add like this

<?
$arr = array(1,2,3,4,5);
$jsarr = implode(',',$arr);
$smarty->assign(arr,$jsarr);
?>

in template file use it like this

<html>
<head>
<script type="text/javascript">
var array = new Array({$arr});
</script>
</head>
</html>
share|improve this answer

It is better to use [] instead of new Array. You need to put values in quotes and escape them - to be sure not to break js. I realy don't like preprocessing data in php just to assign it to smarty. This solves all potential problems:

<script type="text/javascript">
    var arr=[
    {foreach name=i from=$myarray item=v}
      '{$v|escape:"javascript"}'
      {if !$smarty.foreach.i.last},{/if}
    {/foreach}
    ];
</script>

if your array contains only integers the you can use {$v|intval}

share|improve this answer

Since PHP is parsed prior to any JS, you can simply add the values from the PHP array into a JS function:

So if you have this array in PHP:

$my_array = array("a","b","c","d","e");

Then you can use the following to initialize a JS array with the same values:

<?php
    //PHP snippet to create a comma-delimited string with each value of $my_array
    //surrounded by quotation marks.  Quotes not needed if values in array are numeric.
    $array_vals = '"' .implode('","', $my_array) .'"';
?>
<script type="text/javascript">
    var my_array = [<?php echo $array_vals;?>];
</script>
share|improve this answer
    
Do not use new Array! If you have new Array(12) array of 12 elements will be created. But if you have new Array(12,13) array of 2 elements [12,13] will be created. If you assign array with only one element your code will not work as expected. See Arrays –  DamirR Jan 13 '12 at 11:46
    
@DamirR Of course you're right - edited my answer to correct that - thanks for pointing it out. –  TheOx Jan 13 '12 at 14:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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