How to Convert PHP Array to Javascript Object

To convert a PHP array to a JavaScript object, use the “json_encode()” function to generate a JSON representation of the array, then embed it in JavaScript.

Here’s a step-by-step guide on how to do it:

Step 1: Create a PHP array

<?php

$array = [
   "name" => "John",
   "age" => 30,
   "city" => "New York"
];

Step 2: Convert the PHP array to JSON

The json_encode() function is used to convert the PHP array to a JSON string.

<?php

$array = [
  "name" => "John",
  "age" => 30,
  "city" => "New York"
];

$jsonData = json_encode($array);

Step 3: Embed the JSON data into a JavaScript script

<script>
  var data = <?php echo $jsonData; ?>;
  console.log(data);
</script>

The resulting HTML would look something like this:

<script>
  var data = {"name":"John","age":30,"city":"New York"};
  console.log(data);
</script>

Step 4: Accessing the JavaScript object

In your JavaScript, you can access the data object’s properties just like any other JavaScript object.

console.log(data.name); // Outputs: John 
console.log(data.age); // Outputs: 30 
console.log(data.city); // Outputs: New York

This method is effective when dynamically generating JavaScript data from PHP. However, be cautious about embedding sensitive or private data, as this will be visible to anyone who views the page’s source.