Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So hi guys,

lets make this very clear. In php i used json_encode(...) and then got the value in javascript, looks as the following:

["float","float","float","float"]  // PS: This is a string...

And i would like to make this into a normal javascript array, like so:

Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float

And now I'm asking you, how is this possible?

Thank You

share|improve this question
if you passed the array back using json_encode() you have an array and you can index it by the method you showed... – scrappedcola Dec 21 '12 at 17:53
possible duplicate of Pass a PHP array to a JavaScript function – hotveryspicy Dec 22 '12 at 9:19

2 Answers

up vote 1 down vote accepted

It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().

var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);

If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.

var myArray = <?php echo json_encode($myPhpArray); ?>;
share|improve this answer
var myArray = <?= json_encode($myPhpArray); ?>;

Pretty simple. ;-)

Example:

<?php
  $myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
  var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>

Should output (view-source):

<script type="javascript">
  var myJsArray = ["foo","bar","baz"];
</script>

Example

share|improve this answer
And that gives me the javascript array? – Miguel P Dec 21 '12 at 17:51
yes. it's taking an PHP variable and converting in to JSON which javascript will be able to parse and store. – Brad Christie Dec 21 '12 at 17:52
1  
As an explanation it might be helpful to note that JSON (JavaScript Object Notation) is a subset of the JavaScript language and so can be parsed successfully by any JavaScript interpreter. – dualed Dec 21 '12 at 17:58
Indeed, JSON!=JavaScript, it's just a serialized representation of data that JavaScript (and many other languages) can translate. – Brad Christie Dec 21 '12 at 18:00

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.