Converting PHP Multi-dimensional Array to JAVASCRIPT Array – Using JSON encoding

As you know PHP is a Server-side Scripting language. It executes only at the time of page loading and reaches response to the browser as HTML. So PHP multidimensional array cannot assign to JavaScript array directly, since JavaScript is a Client-side Scripting language. That means it runs inside the browser.

So when you need to use multi-dimensional array (from database or elsewhere) as JavaScript array, a better way to do this is the use of JSON array, which is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

First convert the PHP array to JSON array using json_encode function in PHP.

For example,

$json_array=json_encode($data);   // $ data is a multidimensional PHP array.

Now $json_array is JSON Array. It can be used as JavaScript array in PHP after parsing using jQuery.

Don’t forget to include jQuery to your PHP page to use jQuery.parseJSON() function. (If you are not using any jQuery, download from

// In JavaScript
var jsonObj = jQuery.parseJSON('<?php echo $json_array; ?>');

Now jsonObj is a JavaScript multidimensional array.

Follow Mohammed Safeer On twitter.


2 thoughts on “Converting PHP Multi-dimensional Array to JAVASCRIPT Array – Using JSON encoding

  1. all very well until you want to put the function in a .js file, then the php ~ won’t work!
    please can you provide an example for a similar function to operate in a .js file?

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s