5

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.

2
  • how are you doing it now? when do you need to initiate it? Commented Aug 12, 2011 at 13:28
  • 2
    I would use json_encode to encode the object as JSON. JSON is perfect when working with JS. Commented Aug 12, 2011 at 13:29

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

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.