Pass PHP Array to JavaScript (Tutorial)

It turns out you can get PHP and JavaScript to agree on something, and that something is the JSON data format.

Published Categorized as JavaScript, PHP, Web Dev

Arrays are the PHP programmer’s best friend. Not only do they let you store a list of items under a single variable name, each with its own index, but they also make it easy for you to perform operations on a single one or the bulk of them.

But what if you had the task of passing an array that exists on the server side, in your PHP application’s memory, to the client side as an array in JavaScript?

Well, let’s just say I have good news for you:

Not only is this possible, but, thanks to the json_encode() function in PHP version 5.2 and newer, it’s easier to do than you probably think.

How This Works

To pass data from one scripting language to another, you need a common data format—a shared language for data objects, if you will—that you can output from the one and input in the other.

JSON, which stands for JavaScript Object Notation, is that data format in the case of PHP and JavaScript. It has a simple syntax that stores data in key/value pairs, separated by commas, with curly braces to hold strings and square brackets to hold arrays.

Here’s how a JSON representation of Game of Thrones’ John Snow looks like:

// JSON representation (beautified) of John Snow
{ "firstName" : "John", "lastName" : "Snow", "location" : "Thawing Free Lands" }

The question is, how do you generate this JSON representation from your PHP array and ingest it in JavaScript?

The json_encode() Function

Supported from PHP version 5.2 and above, json_encode() is a handy PHP function that takes a value as a parameter, encodes it in JSON data format, and, on success, returns it as a JSON string. (On failure, it will return false.)

You can then use the JSON.parse() method in JavaScript to take that JSON string and construct a JavaScript array with it.

The json_encode() function’s syntax is:

<?php
json_encode(value, options, depth);
?>

Where value is required, and options and depth are optional. (Read more about these optional parameters at W3Schools.)

But enough chit-chat. Let’s get to the meat of it—the implementation example!

Example

Suppose that, in our PHP application, we had a person array storing the first name, last name, and location of John Snow.

Let’s see how we can use the json_encode() function to take the values of that array, encode them in JSON format, then output them to the screen:

<?php
// Store John Snow's details in an array
$person = array('firstName' =>'John', 'lastName' => 'Snow', 'location' => 'Thawing Free Lands');

// Transform his details to JSON format and output them to the screen
echo json_encode($person);
?>

The output to the above function is as follows:

// Output of PHP function above
{"firstName":"John","lastName":"Snow","location":"Thawing Free Lands"}

So how do you make use of this on the frontend, some of you may be wondering?

You could use PHP to echo the result of json_encode() into a variable declared in JavaScript and use the JSON.decode() function in JavaScript to convert it from a string to an array:

<!-- This happens server side -->
<?php
// Store John Snow's details in an array
$person = array('firstName' =>'John', 'lastName' => 'Snow', 'location' => 'Thawing Free Lands');
?>

<!-- This happens client side -->
<html>
<head>
<script>
function jsonStringToJsArray() {
  // Store JSON string in myJSONstring
  let myJSONstring = <?php echo json_encode($person); ?>;
  // Parse JSON string and store in myArray array
  let myArray = JSON.parse(myJSONstring);
}
// Log
console.log(jsonStringToJsArray());
</script>
</head>
<body>
</body>
</html>

Compatibility

The json_encode() function is part of the JSON extension. As of PHP 8, the JSON extension is a core PHP extension that’s always there and is turned on by default. (If your server is running a legacy PHP version, you will have to install and/or configure it.)

Image courtesy of William Perugini /Depositphotos

Leave a comment

Your email address will not be published.