How to Convert PHP Array into Javascript Array

Creating our PHP Array

First we are going to create our PHP array.
  1. <?php
  2. //create example array
  3. $array = array(
  4. 'id' => '1',
  5. 'firstname' => 'neovic',
  6. 'lastname' => 'devierte'
  7. ),
  8. 'id' => '2',
  9. 'firstname' => 'gemalyn',
  10. 'lastname' => 'cepe'
  11. ),
  12. 'id' => '1',
  13. 'firstname' => 'julyn',
  14. 'lastname' => 'divinagracia'
  15. )
  16. );
  17.  
  18. ?>
The above code will create an array that looks like this: php array

Converting into Javascript Array

Finally, we convert our created PHP array into Javascript array.
  1. <script type="text/javascript">
  2. //converting php array to js array
  3. var array = <?php echo json_encode($array); ?>;
  4. console.log(array);
  5. </script>
In here, we will view the created javascript in the console and it will look something like this: json_encode array

Full Source Code

Here's the Full Page Code.
  1. <?php
  2. //create example array
  3. $array = array(
  4. 'id' => '1',
  5. 'firstname' => 'neovic',
  6. 'lastname' => 'devierte'
  7. ),
  8. 'id' => '2',
  9. 'firstname' => 'gemalyn',
  10. 'lastname' => 'cepe'
  11. ),
  12. 'id' => '1',
  13. 'firstname' => 'julyn',
  14. 'lastname' => 'divinagracia'
  15. )
  16. );
  17.  
  18. ?>
  19. <!DOCTYPE html>
  20. <html>
  21. <head>
  22. <meta charset="utf-8">
  23. <title></title>
  24. </head>
  25. <body>
  26.  
  27. <script type="text/javascript">
  28. //converting php array to js array
  29. var array = <?php echo json_encode($array); ?>;
  30. console.log(array);
  31. </script>
  32. </body>
  33. </html>
That ends this tutorial. Happy Coding :)

Add new comment