How to convert PHP array to JavaScript code?

Spread the love

Sometimes, we want to convert PHP array to JavaScript code.

In this article, we’ll look at how to convert PHP array to JavaScript code.

How to convert PHP array to JavaScript code?

To convert PHP array to JavaScript code, we call json_encode to convert the PHP array to JSON.

For instance, we write

<script type='text/javascript'>
<?php
$php_array = array('foo','bar','baz');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>

to create the $php_array array.

Then we call json_encode with it to convert it to a $js_array` JSON array string.

Then we echo the JavaScript code string with $js_array concatenated into the string.

Conclusion

To convert PHP array to JavaScript code, we call json_encode to convert the PHP array to JSON.

Leave a Reply

Your email address will not be published.