Passing a PHP array to JavaScript

This is a guide on how to pass PHP arrays to JavaScript.

Converting your array into JSON.

The best approach is to transform the array into JSON before passing it to the script in question.

To convert your PHP array into JSON, you can use the json_encode function, which will return the JSON representation of the value that you have passed it.

For example, let’s say that we have a basic associative array that looks like this:

Now, let’s say for example that we want to pass the $cartInfo array to one of our JS scripts so that we can do some client-side wizardry. The first thing we’ll do is convert it in JSON:

If you echo out the $cart_info_json variable above, you’ll see that we’re left with a string that looks like this:

Then, in our JavaScript, we’ll do something like this:

Like with all JavaScript variables, you can use the console.log function to dump out its structure to the console. In our example, the variable obj will look like this:

This means that we can now access the data like so:

Hopefully, this article helped!