How to Convert PHP Array into JavaScript Array

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function, PHP array can be converted to JavScript array and accessible in JavaScript. whatever the array type is a single or multidimensional or indexed or associative array. You must have tried this method when you have created API in PHP to transfer data form one server to other server because JSON travel so fast compare to other format and easily accessible in PHP and Javascript.
In PHP

var $booksArray = array("Book-1", "Book-2", "Book-3");

In Javascript
Access Above PHP Array in javascript.

<script>
var books = <?php echo json_encode($booksArray); ?>;
</script>

Access array element in javascript.

console.log(books[2]); // Output will be: Book-3
// OR
alert(books[0]); // Output will be: Book-1



Multidimensional Array

In PHP

$booksArray = array( 
               array('title'='Book-1', 'isbn'=>'12345'),
               array('title'='Book-2', 'isbn'=>'13344'),
               array('title'='Book-3', 'isbn'=>'00440')
             );

In Javascript
Access Above PHP Array in javascript.

<script>
var books = <?php echo json_encode($booksArray); ?>;
</script>

Access array element in javascript.

console.log(books[0]['title']); // Output will be: Book-1
// OR
alert(books[1]['isbn']); // Output will be: 13344



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.