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.
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.
In our example, the variable obj will look similar to this.
Object cart_total: 34.23 currency: "USD" num_cart_items: 3 __proto__: Object
This means that we can now access the data like so.