2

I want to pass php variable into html for further processing. this is php variable-

$coords   = array();

array_push($coords,some value);

I want to pass this to html-

var Coordinates = [];
Coordinates.push('<? php $coords; ?>');

But this is not the correct way as it gives error. Someone please help me to achieve this

Thanks.

Shivam Pande
  • 184
  • 2
  • 14

3 Answers3

4

The simplest example is to json_encode this out into the javascript var like so:

var Coordinates = <?= json_encode($coords) ?>

Then simply loop through this like you would any other json.

This question has been asked alot of times before however, so please check here for any further methods.

How to pass variables and data from PHP to JavaScript?

Juakali92
  • 1,155
  • 8
  • 20
1

Try something like that:

Coordinates.push('<?="[".implode($coords,",")."]" ?>');

http://php.net/manual/en/function.implode.php

1

Server side, you can create a javascript array directly in your rendered html :

<script>
    var Coordinates = [<?php
        echo '"'.implode('","', $coords).'"';
    ?>];
</script>
tmaz
  • 31
  • 3