Convert PHP Array to Javascript JSON

Kevin Amayi Jan 30, 2023 Feb 06, 2022 PHP PHP Array
  1. Convert PHP to Javascript JSON Using json_encode Method
  2. Convert PHP to Javascript Array Using the PHP implode Method
  3. Convert PHP Into Javascript Array Using the PHP implode Method Inside Javascript Array
  4. Use PHP Directly in Javascript
Convert PHP Array to Javascript JSON

We will introduce how to convert PHP into Javascript JSON using the json_encode Method.

Save the below code in the file filename.php. You will need to run this code from a server like Apache with PHP installed.

Convert PHP to Javascript JSON Using json_encode Method

<?php
    $ages = array("Kevin"=>24, "Donald"=>23, "Alvin"=>27);
    echo json_encode($ages);
?>

Output:

{"Kevin":24,"Donald":23,"Alvin":27}

Convert PHP to Javascript Array Using the PHP implode Method

<?php

    function generateJavascriptString($s)
    {
       return '"' . addcslashes($s, "\0..\37\"\\") . '"';
    }

    function generateJson($array)
    {
       $temp = array_map('generateJavascriptString', $array);
       return '[' . implode(',', $temp) . ']';
    }
    var_dump(generateJson(array("Kevin","Amayi","Musungu")));
?>

Output:

"["Kevin","Amayi","Musungu"]"

Convert PHP Into Javascript Array Using the PHP implode Method Inside Javascript Array

<script>
    var js_array = [<?php echo '"'.implode('","',['Programming', 'Coding']).'"' ?>];
    console.log(js_array);
</script>

Output:

Array["Programmig","Coding"]

Use PHP Directly in Javascript

<!DOCTYPE html>
<html>
   <body>
       <?php
          $sevenMultiples =array(7,14,28,35,42,49);
      ?>
  <script type="text/javascript">
    var jsArray = new Array();
    <?php
         $seveMultipleArray=count($sevenMultiples);
         for($i=0;$i<$seveMultipleArray;$i++)
         {
           echo "jsArray[$i] = ". $sevenMultiples[$i] . ";\n";
         }
    ?>
   console.log(jsArray);
   </script>
 </body>
</html>

Output:

Array(6) [ 7, 14, 28, 35, 42, 49 ]

Related Article - PHP Array

  • Determine the First and Last Iteration in a Foreach Loop in PHP
  • Convert an Array to a String in PHP
  • Get the First Element of an Array in PHP
  • Echo or Print an Array in PHP
  • Delete an Element From an Array in PHP
  • Remove Empty Array Elements in PHP