JavaScript array from PHP string

I am developing an application that has over a thousand values. I am trying to create a dynamic array in JavaScript. I am using AJAX to get my values. So I need to create a string from PHP, it should be able to convert from string to array in JavaScript.

How can I create a string in PHP that can be converted to an array in JavaScript?

+3


source to share


3 answers


You are looking for JSON and json_encode () :

$string = json_encode($array);

      



The content of the string will be an array written in valid javascript.

+8


source


Use JSON notation to create a string of values ​​and then read it from JS. The easiest way to do it is this:



<script type="text/javascript">
var myPHPData = <?php echo json_encode($myData); ?>;
alert myPHPData; // now you have access to it in JS
</script>

      

0


source


If you are not going to use json you can do something like this.

you can create a string like this in php (split it by any delimiter)

      $arr = "1;2;3;4;5;6;7" ;

      

in javascript you can convert this to array with split function

      //make an ajax call and get this string (say str)
      arr = str.split(";");

      

split () returns an array

 arr[0] is 1  
 arr[1] is 2
 and so on !!

      

0


source







All Articles