Passing a PHP array to JavaScript.

In this guide, we are going to show you how to pass a PHP array to your JavaScript code.

This is extremely useful if you need to pass data from the server to your JS code without using an AJAX request.

Convert your array into JSON.

The best approach is to convert your array into a JSON string and then pass it to your JavaScript.

To convert your PHP array into JSON, you can use the json_encode function. This function 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.

$cartInfo = array(
    'num_cart_items' => 3,
    'cart_total' => 34.23,
    'currency' => 'USD'

Now, let’s say that we want to pass the $cartInfo array to one of our JS scripts so that we can do something on the client’s side.

The first thing we’ll do is convert it in JSON.

//Our PHP array.
$cart_info = array(
    'num_cart_items' => 3,
    'cart_total' => 34.23,
    'currency' => 'USD'

//Convert the array into a JSON string.
$cart_info_json = json_encode($cart_info);

If you echo out the $cart_info_json variable above, you will see that we are left with a string that looks like this.


Pass it to your JavaScript code.

After we have done that, we can pass the JSON string to our JavaScript like so.

<script type="text/javascript">
    var obj = JSON.parse('<?= $var; ?>');

Like with all JavaScript variables, you can use the console.log function to dump out its structure to the browser console.

In our example, the variable obj will look similar to this.

    cart_total: 34.23
    currency: "USD"
    num_cart_items: 3
    __proto__: Object

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

<script type="text/javascript">
    var obj = JSON.parse('<?= $cart_info_json; ?>');
    alert("There are " + obj.num_cart_items + " cart items.");

And there you have it! Your PHP array is now accessible as a JavaScript variable.