-1

Possible Duplicate:
Best method for converting a PHP array to javascript

I am trying something like this:

<script>
  var product_name = new array();
  <?php
    foreach($products as $key=>$value) {
      echo "product_name[] = $key";
    }
  ?>
</script>

But I could not convert the PHP array to a Javascript array.

7
  • 4
    Look for json_encode() instead :) Commented Nov 14, 2012 at 7:00
  • @Jack I could not able to regard this question as duplicated question. It allow us to demonstrate the topic of the older question in more simple and easy way. Commented Nov 14, 2012 at 7:19
  • @Jack Since 2001, before I hear about json, I send my PHP arrays to be client-side arrays for Javascript. It is just how to print the variable. Commented Nov 14, 2012 at 7:22
  • @sємsєм What can I say, it's not 2001 anymore :) Commented Nov 14, 2012 at 7:23
  • 1
    @Jack Simple always remains simple. This is the main idea. Commented Nov 14, 2012 at 7:25

1 Answer 1

1
<script>
var product_name = new Array();
<?php
    $i = 0;
    foreach($products as $key=>$value)
    {
      echo 'product_name['.$i.'] = '.$key.';';
      $i++;
    }
?>
</script>

Better approach would be using json_encode().

4
  • I used your syntax but it is not working. Commented Nov 19, 2012 at 5:58
  • I can use json_encode() in php end but how can I use that in javascript end, when I need array key, then I would like to search the values of that array for specific values of that key. Commented Nov 19, 2012 at 6:03
  • i've modified a bit. think it'll work now. Commented Nov 19, 2012 at 9:23
  • yours one is not working. I used the below one ` product_array["<?php echo $i;?>"] = "<?php echo $key;?>"; ` Thanks Commented Nov 20, 2012 at 9:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.