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 the php array from java script using json_encode. how to convert this array into java script array

code.

<?php 
  $dataArray = array("Task","Hours Per Day");
  $arr1 = array("Work","Eat","Commute","Watch TV","Sleep");
  $arr2 = array(110,2,2,2,7);
?><html><head></head><body>
  <script type="text/javascript">
    var jArray =<?php echo json_encode($dataArray); ?>;
    var jArray1 =<?php echo json_encode($arr1); ?>;
    var jArray2 =<?php echo json_encode($arr2); ?>;
  </script>
</body>
</html>
share|improve this question

marked as duplicate by Alnitak 19 mins 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.

2  
this should be closed simply because of the sheer lack of research effort –  Alnitak 28 mins ago
    
So what markup does this actually generate? –  RobG 20 mins ago
    
@RobG why is that relevant? –  Alnitak 19 mins ago
    
@Alnitak—presumably the result of <?php echo json_encode($dataArray); ?> is (intended to be) a javascript array literal. Whether or not it produces the expected result will help. –  RobG 10 mins ago

2 Answers 2

You don't need to.

<script type="text/javascript">
    var jArray = <?php echo json_encode($dataArray); ?>;
    console.log(jArray);
</script>

Check the conosle output (F12 in most browsers), it's already an array.

share|improve this answer
    
it will return a json string not an array –  yiiframe 23 mins ago
    
actually, it is Ok after all - the string literal (without the quotes) will be inserted into the JS source at which point it will actually be a well formed array. –  Alnitak 20 mins ago
var arr = Object.keys(yourJsonvariable).map(function(k) { return yourJsonvariable[k] });
console.log(arr)
share|improve this answer

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