How to Convert PHP Array into Javascript Array

Submitted by: 
Language: 
Visitors have accessed this post 302 times.

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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.