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.

Community
  • 1
  • 1
kpp
  • 800
  • 2
  • 11
  • 27

1 Answers1

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
}
TheWolf
  • 1,385
  • 7
  • 16
  • 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. – Klemen Tusar Mar 26 '14 at 11:33
  • this solved it. thanks . I got too used to using foreach loops I guess. – kpp Mar 26 '14 at 11:38