How to convert a PHP array into a Javascript Array?

It may sound bit complex to convert a PHP array into a Javascript array but in reality it is easy. Lets see how can we convert a PHP array into a Javascript array.

<html>
<head>
<title>PHP Array To Javascript Array</title>
</head>
<body>
<script>
//declare an empty array
let fruitNames=[];
</script>
<?php $fruitNames=array("apple","banana","guava","orange"); ?>
<?php foreach($fruitNames as $fname){ ?>
<script>fruitNames.push("<?php echo $fname;?>");</script>
<?php } ?>
<script>
for(let iNum=0;iNum<fruitNames.length;iNum++){
console.log(fruitNames[iNum]);
}
</script>
</body>
</html>
Output: We are going to get following result in the console.

apple
banana
guava
orange
How to convert a PHP array into a Javascript Array? How to convert a PHP array into a Javascript Array? Reviewed by Pixel Stream on December 09, 2019 Rating: 5

No comments:

Powered by Blogger.