I have javascript code some thing like this --
var count=3;
var pl=new Array(count);
var il=new Array(count);
pl.push('<?php echo $var1; ?>');
il.push('<?php echo $var2; ?>');
Why is this not working?
But if I try some thing like this
pl[0]='<?php echo $var1; ?>';
It works. Can some one point out the problem?
Thanks
3 Answers 3
By using the Array constructor you are creating an array with a number of "slots" already defined. In your case, the arrays both have 3 elements when you create them (the value of each element is undefined.)
When you use push, you add an extra element to that array. When you set the element at a specific index, you just set the value of that element.
I would suggest not using the Array constructor, and instead creating array literals:
var pl = [];
var il = [];
pl.push('<?php echo $var1; ?>');
il.push('<?php echo $var2; ?>');
This time, the arrays are created with no elements, so when you use push you are pushing an element into index 0, instead of 4.
Try this:
var pl=[];
var il=[];
pl.push('<?php echo $var1; ?>');
il.push('<?php echo $var2; ?>');
Comments
The new Array(count) creates a new Array object with length set to count, but no indices set. When you print the array, you get array.length times undefined. Now,
array.push(value);
is the same as
array[array.length] = value;
array.length ++;
Which after new Array(3) would set the element number 3 (the 4th element);
pl[0] = '<?php echo $var1; ?>';
pl[1] = '<?php echo $var2; ?>';
pl[2] = '<?php echo $var3; ?>';
does work "correctly"; that is according to the expectations; but you still do not need to initialize the length of array; even doing
var pl = [];
pl[0] = 1;
pl[1] = 2;
pl[2] = 3;
Would still cause the pl.length to be 3.
However your PHP code has a serious flaw that can undermine the security of both your website and the users using it. If $var1 contains a ' character (because it comes from the user or you insert it by accident), you will shoot yourself in the foot - say if $var1 was set to:
$var1 = "'; $.ajax('/user/delete', { method: 'post' }); '"
Please do yourself a favor and use the json_encode function instead to properly quote the values:
var pl = [],
il = [];
pl.push(<?php echo json_encode($var1); ?>);
il.push(<?php echo json_encode($var2); ?>);
or even better notice that you can use the json_encode to readily create arrays, as
var pl = <?php echo json_encode(array(1, 'a', 'b', 5.7)) ?>;
This would produce JavaScript code:
var pl = [1,"a","b",5.7];
You must be careful with the unicode characters U+2028 and U+2029, as these are proper JSON but not proper JavaScript. json_encode does seem to encode them as \u2028 and \u2029 which is safe.
pl.push(10)results in[undefined, undefined, undefined, 10]; whilepl[0] = 10results in[10, undefined, undefined].