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.

This question already has an answer here:

 Array
(
    [0] => Array
        (
            [sno] => 1
            [name] => Sivamani
            [contact] => 750241378
            [$city] => Madurai
        )

)

Array
(
    [1] => Array
        (
            [sno] => 2
            [name] => Guru
            [contact] => 1111111111
            [$city] => Chennai
        )

)

this is my php print_r array how can i get the array length and loop these to print in javascript

share|improve this question

marked as duplicate by Felix Kling, Elias Van Ootegem, Joe Frambach, Joe, Roman C Jun 24 '13 at 14:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
check json_encode –  Elias Van Ootegem Jun 24 '13 at 12:59

4 Answers 4

The best way is json_encode.

PHP > JS:

echo json_encode($array);

in JS:

var array = phpString;

Basically, in PHP, while generating the page, add this:

echo '<script type="text/javascript"> var phpArray = <?= json_encode($yourArray);?>;</script>';

And your PHP array will be made available as a global (evil) variable... you could just as well echo the value in a JS module, and expose it in a more controlled way... but google that for more details...

Anyway, after you've done this:

console.log(phpArray.length);
for (var i=0;i<phpArray.length;i++)
{
    //assoc arrays are objects in JS, hence:
    for(var j in phpArray[i])
    {
        if (phpArray[i].hasOwnProperty(j))
        {
            console.log(j + ' => ' + phpArray[i][j]);
        }
    }
}
share|improve this answer
1  
Why call JSON.parse on client side? The JSON-encoded data should be a valid object literal anyway. –  Sirko Jun 24 '13 at 13:08
    
@Sirko: Damn, you're absolutely right :) will edit my answer... I'm so used to sending data using AJAX, where you do need the JSON.parse call, hence the pointless JSON.parse call –  Elias Van Ootegem Jun 24 '13 at 13:20
    
The JSON.parse was incorrect because the embedded javascript string will go through additional interpolation level before arriving at the JSON parser. So you would have needed var array = JSON.parse('<?php echo javascript_string_escape(json_encode($phpArray)); ?>'); for correct result. Directly doing var a = <?php echo json_encode($phpArray); ?>; is correct by accident in the php json_encode default configuration because of the default unicode escaping. –  Esailija Jun 24 '13 at 14:37
    
@Esailija: I know, I just explained why I made that error. I haven't echo-ed from PHP into JS directly for years. Instead I always use ajax, so it's become a habbit of wrapping all data coming from the server in a JSON.parse call. But I fully understand what my mistake is/was... –  Elias Van Ootegem Jun 24 '13 at 14:40
1  
Yeah that wasn't my point, I am saying JSON.parse is more robust provided you understood to additionally escape for javascript strings. –  Esailija Jun 24 '13 at 14:42

You can use console.log to print to the console: (this is for debugging)

var a = [1, 2, 3];
console.log(a); // [1, 2, 3]

If you want to string an array/object you can use JSON.stringify: (this is a good way to transfer data from frontend to backend)

var a = [1, 2, 3];
JSON.stringify(a); // "[1, 2, 3]"

Also if you want to prettify the stringification you can use the 3. arguments to JSON.stringify:

JSON.stringify(obj, handler, spaces);
JSON.stringify([1, 2, 3], null, "\t");
JSON.stringify([1, 2, 3], null, "    ");
JSON.stringify([1, 2, 3], null, 2); 
share|improve this answer

Try this:

 var data = new Object();
    data["firstname"] = "John";
    data["lastname"] = "Bhutt";
    data["age"] = 29;

    alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
share|improve this answer
    
This is Non Standard and does only works in FireFox? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… –  NULL Jun 24 '13 at 13:03

I am using the PHP json_encode function instead. So your code should be like:

echo json_encode($YOUR_ARRAY);

On the client side you should parse the string and you will get your array. I usually use jQuery for that. Requesting something by AJAX can look like:

$.post(SCRIPT_URL, POST_PARAMS,
    function(response) {
    // YOUR ACTIONS HERE - response is your parsed ARRAY
    },
   'json'
);

You can find details about jQuery.post method here.

share|improve this answer

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