tags:

views:

50

answers:

2

I have this PHP code -

 <?php
for($i=1; $i<=1000; $i++) {
  $array=array();
  $array[$i]=54*$i;

  $arr=array($array[$i].",");

  foreach ($arr as $value) {
    echo $value;
  }
}
?>

I tried with:

var i;
for(i=1;i<=1000;i++) {
  var array = new Array();
  array[i] = 54*i;
  var arr = new Array();
  arr.push(array[i]+",");
}
alert(arr)

But it doesn't work. Where's the mistake?

A: 

Something like this:

var array = new Array(1000);
for(var i=1;i<=1000;i++) { 
    array[i] = 54*i; 
} 
alert(array[1000]) ;

Just a few "pointers" (pun unintended);

  1. You sure don't want all 1000 calls to be echoed to messageboxes - I only display the last (1000 * 54) to the user - clicking Ok 1000 times ...
  2. You don't push anything into an array like Php code. In this case I "define" the arraylength to 1000, but creating an array without the lenght does work to. Just "add" items with arrayName[indexToBeCreated] et voila.
  3. Loop variables don't need to be defined before the loop, just define them inside the loop (for (var i blabla...

Hope it helps

riffnl
Oh ,the alert was for checking if all works correctly.
lam3r4370
+1  A: 

Wild stab.. because the PHP code while it may produce the expected output, is actually 'wrong' (wrong on the basis that you may expect the array to hold all those values, and it doesn't).

so here's the php (fixed).

<?php
$a = array();
$stringVersion = '';
for($i=1; $i<=1000; $i++) {
  $a[$i] = 54*$i;
  $stringVersion .= $a[$i] . ',';
}
echo $stringVersion;

and here's a JS alternative

var a = [];
var stringVersion = '';
for(var i=1;i<=1000; i++) {
  a[i] = 54*i;
  stringVersion += a[i] + ',';
}
alert(stringVersion);
nathan
I'd rather use `stringVersion = implode(',', $a);` after the iteration.
Mikulas Dite
likewise re implode, I had it like that but the js version looked different then and didn't match, so aligned them :)
nathan