-3

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>
5
  • It's hard to tell what your problem is from this question. Commented May 24, 2012 at 11:06
  • 1
    Why do you think it would be empty? battletext has a length of 2. Commented May 24, 2012 at 11:06
  • Where's the empty array? Commented May 24, 2012 at 11:08
  • the emty array in JS looks like this: new Array() Commented May 24, 2012 at 11:10
  • Try $btext = array(); $btext[] = ${'name_'.$user}; echo "var battletext = ".json_encode($btext).";"; Commented May 24, 2012 at 11:11

1 Answer 1

5

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>
6
  • How can I fill the $battletext in a while loop? Commented May 24, 2012 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 Commented May 24, 2012 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 Commented May 24, 2012 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...??? Commented May 24, 2012 at 12:22
  • what happens if you do <? print_r($btext); ?> in the same place in the code? Commented May 24, 2012 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.