Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a PHP array inside a JS For loop

I explored a bunch of related questions but to no avail.
I use json_encode to pass on a PHP variable to JS and it works fine.
<?php echo json_encode($datasets[0]);?>);

But when I try to do the same thing inside a JS for loop using the index of the loop it only picks up null.
How can I use the the index of the PHP array $datasets[] inside a JS for loop?

const DT = [];
    for (let i = 0; i < 10; i++) {
    DT.push(<?php echo json_encode($datasets[i]);?>);
    };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

PHP executes before any of the JavaScript executes, so it cannot evaluate $datasets[i], because that i is not known in PHP. Moreover, it would only evaluate it once, because there is no PHP loop.

The way to do this, is to let PHP pass the whole data set to JavaScript:

const DT = <?php echo json_encode(array_slice($datasets, 0, 10));?>;

If the PHP array is also 10 items long, then you can omit the array_slice part. But if your intention was to just get the first 10 items of a longer PHP array, you’ll need it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading