0

I have a PHP array here:

$newArray = array(4,27,34,52,54,59,61,68,78,82,85,87,91,93,100);

I want this PHP array to be passed on to my JavaScript code to make my 'data' variable in my JavaScript the same as the array I declared on my PHP script. Here is my JavaScript code:

<script type="text/javascript">
$(function() {

    data:  [4,27,34,52,54,59,61,68,78,82,85,87,91,93,100];

});
</script>

My idea is just embed the $newArray directly like this:

data: <?php $newArray ?>

But it doesn't work. How would I do it? Thank you for your help.

2
  • 3
    data: <?php echo json_encode($newArray) ?> Commented Mar 4, 2014 at 17:46
  • @MLeFevre Post that as an answer. Commented Mar 4, 2014 at 17:48

3 Answers 3

1

Just doing

data: <?php $newArray ?>

wouldn't output the contents of $newArray, you'd still need to output as well, by doing either

echo $newArray
print $newArray

(Try that and you'll get a different error ;)) But even then, it won't be in the format that you want, so you'll want to use json_encode encode on it to format in a way that javascript can read it, like so

data: <?php echo json_encode($newArray) ?>;
1
  • You would need to first flatten the array, (like you did with the json_encode) you can't simply echo/print an array Commented Mar 4, 2014 at 17:52
0

Use PHP's built in json_encode() function like this:

$array = array("item_1" => 1, "item_2"=> 2);
$json = json_encode($array);

Then pass that array to your JavaScript (via AJAX or some other method) and decode with the jQuery function $.parseJSON() like this:

$(function(){
    var json = $.parseJSON(passedFromPHP);
});

This will give you a JSON object that you can manipulate with JavaScript.

0

You can also do this:

data: [<?php echo implode(',', $newArray); ?>];

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.