Skip to main content

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 :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.