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.

This question already has an answer here:

I get array from php,and then use to change js array and display but its show all elements as an array.##

$name = array('A','B','C','D');

<script> 
     <?php echo "var name='".json_encode($name)."';";   ?>
     for (var i in name){
                        alert(name[i]);
                         }
</script>
share|improve this question

marked as duplicate by wawawared, Dagon 18 hours ago

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.

1  
Many duplicates on SO, many results in Google :-| –  wawawared 18 hours ago

2 Answers 2

No need to wrap the value in '', if you wrap it the value will be considered as a string not an array in javascript

<?php echo "var name=".json_encode($name).";";   ?>
share|improve this answer
<script type='text/javascript'>
<?php
$name = array('A','B','C','D');
$js_array = json_encode($name );
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>

Reffer this Answer

Note json_encode() is only available in PHP 5.2 and up

share|improve this answer

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