Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Why is my Javascript array empty? In a while loop I fill a variable ($btext). When I echo $btext everything is shown fine:

But if I try to fill the Javascript array nothing is printed there.

This is how I fill the variable $btext in php:

$btext .= "\"".${'name_'.$user}."\",";

Here the Javascript part:

var battletext = new Array(<? echo $btext; ?>);

If I define $btext like:

$btext = "\"Hallo\", \"Welt\"";

the Sourcecode looks like this:

<script>
var battletext = new Array("Hallo", "Welt");
</script>
share|improve this question
It's hard to tell what your problem is from this question. – Gareth May 24 '12 at 11:06
1  
Why do you think it would be empty? battletext has a length of 2. – Bergi May 24 '12 at 11:06
Where's the empty array? – Juhana May 24 '12 at 11:08
the emty array in JS looks like this: new Array() – Quicknation May 24 '12 at 11:10
Try $btext = array(); $btext[] = ${'name_'.$user}; echo "var battletext = ".json_encode($btext).";"; – DaveRandom May 24 '12 at 11:11

1 Answer

You should just use json encode:

$battletext = array( "Hallo", "Welt" );

html:

<script>
var battletext = <?php echo json_encode( $battletext ); ?>;
</script>

source:

<script>
var battletext = ["Hallo", "Welt"];
</script>
share|improve this answer
How can I fill the $battletext in a while loop? – Quicknation May 24 '12 at 11:17
To explain what i like to do: I like to fill in the loop a variable ($btext) and later the JS should step through every part of the variable and show this in a textbox – Quicknation May 24 '12 at 11:20
@Quicknation Instead of string concatenation in your loop ($btext .= ) declare $btext = array() before the loop, and inside the loop use this line: $btext[] = ${'name_'.$user}; - then you have a PHP array of all the names, which json_encode() will translate to a valid Javascript array literal. As a side note, you would do better to use an array in the first place instead of variable variable names – DaveRandom May 24 '12 at 11:22
@DaveRandom: I did it like you discribed. In the source code there is still an empty array: var battletext = <? echo json_encode($btext); ?>; if I echo $btext[1] the name is shown...??? – Quicknation May 24 '12 at 12:22
what happens if you do <? print_r($btext); ?> in the same place in the code? – DaveRandom May 24 '12 at 12:28
show 1 more 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.