Last active
November 14, 2024 22:36
-
-
Save OkoyaUsman/8d085571ea6ed827fdefbe0fba2db8c1 to your computer and use it in GitHub Desktop.
How to Convert PHP Array into JavaScript Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
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. | |
*/ | |
//In PHP | |
var $booksArray = array("Book-1", "Book-2", "Book-3"); | |
//In Javascript | |
<script type="text/javascript"> | |
var books = JSON.parse('<?= json_encode($booksArray); ?>'); | |
console.log(books[2]); // Output will be: Book-3 | |
// OR | |
alert(books[0]); // Output will be: Book-1 | |
</script> | |
// For 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 | |
<script type="text/javascript"> | |
var books = JSON.parse('<?= json_encode($booksArray); ?>'); | |
console.log(books[0]['title']); // Output will be: Book-1 | |
// OR | |
alert(books[1]['isbn']); // Output will be: 13344 | |
</script> | |
?> |
line 13 and 28 should look like this:
var books = JSON.parse('<?= json_encode($booksArray); ?>');
Fixed according to @Misha-in
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is not working