1

I need to use php arrays in my javascript code. The arrays are defined in PHP in the same file as the javascript.

I have tried the following two ways:

var array_name = new Array('<?php echo implode("','", $php_array);?>');

and

var array_name = <?php echo json_encode($php_array);?>;

This works great if my php arrays are integers. However, when I try to do either when the array is a list of strings, then it does not work.

Any suggestions on what other options I have?

Any help appreciated.

1

1 Answer 1

1

put that json string into quotes (single quotes!)

var array_name = '<?php echo json_encode($php_array);?>';

enjooy

2
  • Thanks! As I went to enter the quotes in, I found my mistake; I forgot an '='. I've also discovered that it works both ways--quotes or not.
    – Marina
    Commented Aug 1, 2011 at 22:31
  • @Marina: yes but with your one it's not json but class javascript array :)
    – genesis
    Commented Aug 1, 2011 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.