How to assign PHP array values to JavaScript array

All we need is an easy explanation of the problem, so here it is.

How to assign PHP array values to JavaScript array?

Using below PHP code I am storing data in PHP array:

$str_query="SELECT title,description FROM tablename ORDER BY title";

$schd_arr = array();
$schd_arr[$int_count] = $rs_sch->Fields("title").": ".$rs_sch->Fields("description");

Using below JavaScript code I am trying to store PHP array data into JavaScript array

What and how to write variable at below 2 mentioned locations so my code can work?

<script type="text/javascript" language="javascript">
var pausecontent=new Array()
for (sch_cnt=0; sch_cnt<*Here I want to assign value of $int_count php variable*; sch_cnt++)
pausecontent[sch_cnt]=<?php *Here I want to assign php array and counter values (something like this - $schd_arr[sch_cnt];)* ?>;

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can directly use the json_encode function. It is easy to use and produces valid javascript so is very stable:

<script type="text/javascript">
    var pausecontent = <?php echo json_encode($php_array); ?>;

Method 2

You can’t loop like that, you need to loop the PHP array and push into javascript array:

<script type="text/javascript" language="javascript">
    var pausecontent = new Array();
    <?php foreach($schd_arr as $key => $val){ ?>
        pausecontent.push('<?php echo $val; ?>');
    <?php } ?>

Method 3

I think you’d best get the array to your javascript first. That would be something like this:

var theVariableYouWantTheArrayIn = <?php echo json_encode($theArrayYouWantInJavascript); ?>

After that it is a normal js array, so you can use properties like .length which will presumably make the loop much easier.

Method 4

I had the same problem doing this but finally found the best solution

    var arr=[];
        $query = "SELECT *FROM c group by name";
        $res = mysqli_query($conn,$query) or die(mysqli_error($conn));

        while($data = mysqli_fetch_array($res))

             echo $data["name"];

Method 5

Above both answers in good.

  1. Iterate through the array you got as a result of your DB query and add each value to a new PHP variable,
  2. Add a counter and increment it during each iteration to make sure that you’re not adding a comma after the last element,
  3. If the count of the elements in the array is more than 1, create the array as usual, otherwise create a new array with 1 element and assign your PHP array value to the index 0.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply