How to Convert PHP Array into JavaScript Array

JavaScript Array, search value increase PHP Execution Time connect multiple database display source code save image Export MySQL Database configure mongodb send email from localhost

You can easily use PHP Array in JavaScript Array you unaided dependence to convert PHP array into JSON format Using json_encode() put it on, PHP array can be converted to JavScript array and accessible in JavaScript. everything the array type is a single or multidimensional or indexed or associative array. You must have tried this method once you have created API in PHP to transfer data form one server to count server because JSON travel as a consequences hasty compare to added 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