How to pass or use PHP array in Javascript variable?

Multidimensional PHP arrays are similar to multidimensional JSON objects. So shouldn't be there a way to use a multidimensional PHP array in Javascript? Obviously, and there is ways. For example you can use AJAX to make a request and get the PHP back in JSON format. However, why to make an AJAX call if the array is ready to be used already? Right.

If the PHP array is ready to be used in Javascript already, then just simply echo the PHP array in a Javascript variable as follows.

$settings = array(
 'id' => 'mydemoWidget',
 'status' => 'active',
 'configuration' => array(
  'title' => 'Demo Title',
  'style' => array(
   'background-color' => '#fff',
   'border' => true,
  'content' => array(
   'category' => null,
   'page' => 5,
   'tags' => array(5,4,3),
   'start' => 0,
   'total' => 10
<script type="text/javascript">
var $settings = <?php echo json_encode($settings)?>;

So that's it.


You can also ECHO any PHP variable to JS variable. Just don't forget to use quotation around the PHP tag in case of string, json_ecnode the variable if it is an array.

$an_array = array();
$a_string = "I am string";
$a_numeric = 5;
<script type="text/javascript">
var $an_array = <?php echo json_encode($an_array)?>;
var $a_string = "<?php echo $a_string?>";
var $an_array = <?php echo $a_numeric?>;

Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us