Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a multidimensional PHP array to javascript

Tags:

javascript

php

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.

like image 243
etm124 Avatar asked Aug 12 '11 13:08

etm124


1 Answers

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.

like image 82
J0HN Avatar answered Sep 26 '22 15:09

J0HN