Press "Enter" to skip to content

How to Convert PHP Array into JavaScript Array

0
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
 
 

Multi Dimension

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

 
Why Python Programming Language is very useful for Hackers?
How to add multiple image Bootstrap Slider in your Website