Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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.

share|improve this question
2  
for(var x in ar){ alert(ar[x]); } – أنيس بوهاشم Mar 26 '14 at 11:26
    
syntax was wrong in this screen, but not in my editor just took wrong over from my editor. – kpp Mar 26 '14 at 11:39

1 Answer 1

up vote 0 down vote accepted

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
}
share|improve this answer
    
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. – techouse 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

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.