How to Convert a PHP Array to a JavaScript Array

PHP allows converting a PHP array to JavaScript. It is considered a common practice for most developers.

Let’s see multiple ways of using the json_encode function to convert a PHP array to JavaScript.

You should take into account that technically it will be within the JSON format. Also note that before applying this function, you should make sure to have PHP 5.2 version or above.

The syntax of the json_encode function is as follows:

json_encode( $my_array );

Convert a PHP array to a JavaScript JSON Object

As it was mentioned above, in PHP, you can use the json_encode function for converting PHP arrays into JavaScript.

Below, you can figure out how to convert a PHP array into a JavaScript JSON object:

<?php 
// Array in php
$myArr = ['W3docs', 'W3docs.com']; 
?>
  
<!-- Convert a PHP array into a JavaScript array -->
<script>
const arr = <?php echo json_encode($myArr); ?>;
document.write(arr[1]);
</script>

The output of this example will be:

W3docs.com

Convert a Single Dimensional PHP Array to JavaScript

Now, let’s get to discovering how to convert a single dimensional PHP array to a JavaSCript array with the help of json_encode($myArr). We convert a PHP array to a JavaScript array by passing it and then applying json_encode like this:

<script type='text/javascript'>
<?php
$php_array = ['W3docs', 'for', 'W3docs'];
$js_array = json_encode($php_array);
echo "const javascript_array = " . $js_array . ";\n";
?>
document.write(javascript_array[0]);
</script>

The output of this example is:

W3docs

Convert a Multi-dimensional PHP Array into a JavaScript Array

Here, you will discover how to convert a multi-dimensional PHP array to a JavaScript array.

To convert a PHP array to a JavaScript array, you should pass it and then apply json_encode.

Here is an example:

<script type='text/javascript'>
  
<?php
$php_array = [['W3docs', '[email protected]'], ['for', '[email protected]']];
$js_array = json_encode($php_array);
echo "const javascript_array = " . $js_array . ";\n";
?>
  
document.write(javascript_array[0][1]);
</script>

The output of this example will look like this:

for@example.com

Description of the json_encode Function

This function is used for returning a string that contains a JSON representation of the provided value.

Its encoding is impacted by the provided options. Additionally, the encoding of float values relies on the value of serialize_precision.

For more information about the json_encode function and its usage, you can check out this page.