I have an array($my_array) that looks something like:

array(2) {
[25]=>int(10)
[30]=>int(8)
}

I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?

Edit: At first, I thought I could just assign it like a string, but that isn't working:

var photo_limit = $my_array;

I tried also doing a var_dump into my js value.

I'm currently trying to use something like:

for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}

Thanks.

share|improve this question
how are you doing it now? when do you need to initiate it? – Kasia Gogolek Aug 12 '11 at 13:28
2  
I would use json_encode to encode the object as JSON. JSON is perfect when working with JS. – Jay Aug 12 '11 at 13:29

2 Answers

up vote 9 down vote accepted

The best way is to use json_encode. See json_encode reference

Used like this:

<script>
var array = <?php echo json_encode($array)?>;
</script>

Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.

share|improve this answer

1: json_encode your PHP array.

2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)

<script>
    var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>
share|improve this answer

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.