PHP

How to Convert PHP Array to Javascript Array in PHP


In this article, you will learn how to PHP array to Javascript array in PHP.

Let’s say you have an array of strings.

$a = array(
          0 => "Apple", 
          1 => "Banana", 
          2 => "Cherry", 
          3 => "Durian",
          4 => "Elderberry",
          5 => "Fig");

Convert PHP Array to Javascript Array

In order to convert a PHP array to a Javascript array, you can use the json_encode() method.

$a = array(
          0 => "Apple", 
          1 => "Banana", 
          2 => "Cherry", 
          3 => "Durian",
          4 => "Elderberry",
          5 => "Fig");

echo json_encode($a);
// ["Apple","Banana","Cherry","Durian","Elderberry","Fig"]

Note: The json_encode() method functions by parsing the supplied input into a JSON representation.


Share on social media

//