How to pass a PHP string to a JavaScript variable?

Spread the love

Sometimes, we want to pass a PHP string to a JavaScript variable.

In this article, we’ll look at how to pass a PHP string to a JavaScript variable.

How to pass a PHP string to a JavaScript variable?

To pass a PHP string to a JavaScript variable, we echo the value we want in the JavaScript code.

For instance, we write

<script>
  let myVar = <?php echo json_encode($myVarValue); ?>;
</script>

to echo the value of the $myVarValue associative array converted into a JSON string with json_encode.

The JSON string will be automatically interpolated as a JavaScript object.

And then we assign the object to myVar.

Conclusion

To pass a PHP string to a JavaScript variable, we echo the value we want in the JavaScript code.

Leave a Reply

Your email address will not be published. Required fields are marked *