0

so I have this code:

var loc = new Array();
        <?php foreach($loc as $key => $val) { ?>
            loc.push('<?php print_r($val); ?>');
        <?php } ?>

The problem is is that it's only showing one value and not more than one, like it should. This is the php array code:

$loc = array($lat, $long);

Any help is greatly appreciated.

2
  • 1
    print_r is only for debugging. It's not for anything else. Commented Feb 27, 2014 at 16:25
  • 1
    Why are you using print_r()? It's only used to display a formatted version of your array and is not to be used for transferring data from client <-> server. Use JSON format instead, as shown in Niet's answer below. Commented Feb 27, 2014 at 16:25

1 Answer 1

9

Try this:

var loc = <?php echo json_encode($loc); ?>;

You should not use print_r. Let me quote the documentation:

print_r — Prints human-readable information about a variable

Note the part I emphasised. "human-readable". Just because it looks vaguely like something JavaScript might understand, doesn't mean it is ;) json_encode, on the other hand, is specifically designed to output JSON, which is a subset of the syntax JavaScript accepts for variables.

Sign up to request clarification or add additional context in comments.

2 Comments

Ninja'd. +1 for being fast (and correct, at the same time).
I think it'd be better to have a short explanation of why the given code doesn't work :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.