user3084625
user3084625

Reputation: 3

PHP to Javascript array trouble

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.

Upvotes: 0

Views: 47

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

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.

Upvotes: 9

Related Questions