Have you ever needed to send a PHP variable, array, or object to JavaScript? It can get complicated trying to escape the output properly. Here’s a way that always works—no escaping necessary.
Let’s say we have the following variable in PHP:
And we want to pass it to a JavaScript variable called name. Here’s the trick:
Using json_encode(), you’ll always get a properly formatted JavaScript object.

The same trick can be applied to other data types (e.g. integers, arrays, objects, etc.). The following passes an entire array from PHP to JavaScript:

The output looks like this:

Don’t want it all on one line? Try this instead:
The output is a bit easier to read:
A simple trick, but nevertheless useful.

Leave a Reply

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