How to Convert PHP Array to Javascript Object

To convert a PHP array to a JavaScript object, you can use the “json_encode()” function in PHP to convert the array to a JSON string and then output the JSON string in a JavaScript script tag.


 // Your PHP array
 $phpArray = [
  'name' => 'John',
  'age' => 30,
  'city' => 'New York'
<!DOCTYPE html>
<html lang="en">
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>PHP Array to JavaScript Object</title>
 // Convert PHP array to JSON string
 const jsonString = '<?php echo json_encode($phpArray); ?>';

 // Parse JSON string to JavaScript object
 const jsObject = JSON.parse(jsonString);

 // Log the JavaScript object to the console

In this example, we first defined a PHP associative array called $phpArray.

In the next step, we used the json_encode() function to convert the PHP array to a JSON string.

We output the JSON string inside the JavaScript script tag using <?php echo json_encode($phpArray); ?>.

Next, we parse the JSON string to a JavaScript object using JSON.parse(jsonString) and store the result in the jsObject variable. Finally, we log the JavaScript object to the console.

Run the above PHP file on a web server with PHP support, and open the file in your web browser. The JavaScript object created from the PHP array will be logged into the browser’s console.

Remember that the JSON string should be properly escaped to avoid issues with special characters. In most cases, json_encode() takes care of this for you, but if you encounter issues, consider using the JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_QUOT, and JSON_HEX_AMP options with json_encode().

Leave a Comment