1
 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

Baba
  • 94,024
  • 28
  • 166
  • 217
cvas
  • 31
  • 1
  • 4

4 Answers4

2

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]);
        }
    }
}
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • 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('');` for correct result. Directly doing `var a = ;` 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
  • @Esailija: Gotcha... sorry, monday, and about to leave work, so I'm not really that focussed anymore. – Elias Van Ootegem Jun 24 '13 at 14:46
0

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); 
Community
  • 1
  • 1
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

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})"
user2504141
  • 67
  • 3
  • 11
  • This is Non Standard and does only works in FireFox? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toSource – Andreas Louv Jun 24 '13 at 13:03
0

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.

maddob
  • 989
  • 1
  • 12
  • 29