0

I was looking for a way to convert a php array into a javascript array.

This was supposed to be done with json_encode as follows. Pass a PHP array to a JavaScript function

I did this with my code but instead of giving me the original array items javascript only gave me the index numbers of the array and the data seems to be gone.

Here is the PHP code.

//creates array.
$ar = array("item 1","item2","etc");

foreach($ar as $item){
    echo $item;
}//prints the array items.(so item1 item2 etc)

Here is the javascript code.

//Supposibly turns the php array into a js array.
var ar = <?php echo json_encode($ar); ?>;

for(var x in ar){
    alert(x);
}//alerts the indexes and not the array items.(so 0 1 2)

Did I miss something important here, since everywhere I search they said json_encode should work. But for me it doesn't.

I do know the arrays are connected because if I add an item to "$ar" then "var ar" also has an extra item.

2
  • 2
    for(var x in ar){ alert(ar[x]); } Commented Mar 26, 2014 at 11:26
  • syntax was wrong in this screen, but not in my editor just took wrong over from my editor. Commented Mar 26, 2014 at 11:39

1 Answer 1

0

The foreach syntax in JavaScript is not meant to be used for arrays, but for objects.

for (var key in obj)

gives you the keys of the object, not the respective values. In order to access those, you would have to use obj[key]. However, JavaScript arrays should rather be iterated over using a common for loop like this:

var length = arr.length;

for (var i = 0; i < length; i++) {
    // Do stuff with arr[i] here
}
2
  • when using for (var key in obj) don't forget to issue if (obj.hasOwnProperty(key)) { //code } each loop run otherwise you might get some unexpected visitors from outer space. Commented Mar 26, 2014 at 11:33
  • this solved it. thanks . I got too used to using foreach loops I guess. Commented Mar 26, 2014 at 11:38

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.