Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am developing an application having more than thousands of values. I am trying to make a dynamic array in JavaScript. I'm using AJAX to get my values. So I have to create a string from PHP ,it should able to convert from string to array in JavaScript.

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

share|improve this question
    
you should make json string in PHP and then json to JS object for javascript logic. json.org/js.html –  Dev Mar 12 '12 at 10:30
1  
This isn't hard to do (json_encode is your friend), but "more than thousands of values" suggests you might want to rethink your application architecture... –  lonesomeday Mar 12 '12 at 10:30
add comment

3 Answers

up vote 7 down vote accepted

You are looking for JSON and json_encode():

$string = json_encode($array);

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

share|improve this answer
    
Thanks for instant comment. Actually i want to know how i can make this string from PHP if values generate by a loop. ? –  Fas K K Fasil Mar 12 '12 at 10:39
    
Fas K K Fasil: json_encode accepts an array, so you need to create an array in PHP first, like $array = array(1, 2, 3). Can't give you exact code, because I don't know how your application works. –  Gergo Erdosi Mar 12 '12 at 10:44
add comment

Use JSON notation to create a string of values and then read it from JS. The simplest way to do this is something like that:

<script type="text/javascript">
var myPHPData = <?php echo json_encode($myData); ?>;
alert myPHPData; // now you have access to it in JS
</script>
share|improve this answer
    
Thanks alot for this commnt. –  Fas K K Fasil Mar 12 '12 at 10:42
    
json_encode is not useful if string generated by ajax. There i used spli(); –  Fas K K Fasil Mar 12 '12 at 10:47
add comment

if you dont intend to use json , you can do something of this kind..

you can create a string of this kind in php (separate it by any delimiter)

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

in javascript you can convert this to array using 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 !!
share|improve this answer
    
Thanks allot.My problem solved. –  Fas K K Fasil Mar 12 '12 at 10:41
    
u r welcome :) you can upvote or accept this answer in that case :) –  vireshas Mar 12 '12 at 10:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.