2

I have this PHP array ($savedRequestDates) of dates:

Array ( [0] => 2018-03-29 10:56:31 [1] => 2018-03-29 10:58:09 [2] => 2018-04-12 11:28:41 [3] => 2018-04-12 13:07:25 [4] => 2018-05-09 13:08:07 ) 

At the bottom of the same .php page I have this:

<script type="text/javascript">
var sessions = new Array('<?php echo json_encode($savedRequestDates); ?>');
console.log(sessions[0]);
</script>

The console.log(sessions[0]); returns:

["2018-03-29 10:56:31","2018-03-29 10:58:09","2018-04-12 11:28:41","2018-04-12 13:07:25","2018-05-09 13:08:07"]

Why is the JavaScript array flattening at the 0 index? If I try console.log(sessions); it returns an array with one variable, not 5, as the php array clearly shows.

Am I missing something here?

2 Answers 2

6

This happens because you're wrapping the array from PHP which another array (new Array). Just remove the new Array part and it will work fine.

var sessions = <?php echo json_encode($savedRequestDates); ?>;
Sign up to request clarification or add additional context in comments.

Comments

0

From what I see the call to json_encodewill create a full JSON object and not just the content of the array. You are enclosing the entire output of the PHP generated array as index 0 inside the new Array.

So removing the new Array will generate what you are looking for.

Try this:

<script type="text/javascript">
var sessions = <?php echo json_encode($savedRequestDates); ?>;
console.log(sessions);
</script>

And you should see the entire array.

1 Comment

That did it! Thank you for the help.

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.