• We just launched and are currently in beta. Join us as we build and grow the community.

How to Convert PHP Array into Javascript Array

Blutzeugen

Bounce Rate Slayer
B Rep
0
0
0
Rep
0
B Vouches
0
0
0
Vouches
0
Posts
35
Likes
145
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
Creating our PHP Array

First we are going to create our PHP array.

  1. <?php
  2. //create example array
  3. $array

    =

    array

    (
  4. array

    (
  5. 'id'

    =>

    '1'

    ,
  6. 'firstname'

    =>

    'neovic'

    ,
  7. 'lastname'

    =>

    'devierte'
  8. )

    ,
  9. array

    (
  10. 'id'

    =>

    '2'

    ,
  11. 'firstname'

    =>

    'gemalyn'

    ,
  12. 'lastname'

    =>

    'cepe'
  13. )

    ,
  14. array

    (
  15. 'id'

    =>

    '1'

    ,
  16. 'firstname'

    =>

    'julyn'

    ,
  17. 'lastname'

    =>

    'divinagracia'
  18. )
  19. )

    ;

  20. ?>

The above code will create an array that looks like this:

initial_array.png

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:

php_array_js.png

Full Source Code

Here's the Full Page Code.

  1. <?php
  2. //create example array
  3. $array

    =

    array

    (
  4. array

    (
  5. 'id'

    =>

    '1'

    ,
  6. 'firstname'

    =>

    'neovic'

    ,
  7. 'lastname'

    =>

    'devierte'
  8. )

    ,
  9. array

    (
  10. 'id'

    =>

    '2'

    ,
  11. 'firstname'

    =>

    'gemalyn'

    ,
  12. 'lastname'

    =>

    'cepe'
  13. )

    ,
  14. array

    (
  15. 'id'

    =>

    '1'

    ,
  16. 'firstname'

    =>

    'julyn'

    ,
  17. 'lastname'

    =>

    'divinagracia'
  18. )
  19. )

    ;

  20. ?>
  21. <!DOCTYPE html>
  22. <html>
  23. <head>
  24. <meta charset="utf-8">
  25. <title></title>
  26. </head>
  27. <body>

  28. <script type="text/javascript">
  29. //converting php array to js array
  30. var array = <?php

    echo

    json_encode

    (

    $array

    )

    ;

    ?>

    ;
  31. console.log(array);
  32. </script>
  33. </body>
  34. </html>

That ends this tutorial. Happy Coding :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,891

323,899

Top