0

I'm passing variables from PHP to JS using the following approach:

var dbGen = parseInt("<?php echo $gen; ?>");

However, I'm struggling a lot to do this from an array (pushing each element from a PHP array to a JS array). This is because there I can't seem to place a JS iterator "i" inside the loop, as it recognizes it as php code:

var dbDNA = [];

for (var i = 0; i < 10; i++) {
    dbDNA.push(parseInt("<?php echo $DNA[i]; ?>"));
}

I also tried writing a function (ES6) that would combine everything as a string and try to execute the php code, but that didn't work either:

function pushToArray(arr, ind){
    let str = `<?php echo ${arr}[${ind}]; ?>`;
    dbDNA.push(parseInt(str));
}

for (var i = 0; i < 10; i++) {
    pushToArray("$DNA", i);
}

Any ideas on how I could solve this?

Many thanks!

1 Answer 1

2

json_encode() is sufficient...

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

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.