PHP Variables in Javascript

I don't have much programming experience. I have some code that I'm adapting and I don't understand how the variables are being passed from PHP to JavaScript. I suspect I'm missing out on a bit of basic theory but I have so far been unable to track it down on the web. Google maps marker information is being passed as follows: -

<?php  
$mrk_cnt = 0;    
while ($obj = $res->fetch_object()){
    $username[$mrk_cnt] = $obj->username;
    $inf[$mrk_cnt] = $obj->title;   
    $lat[$mrk_cnt] = $obj->lat;
    $lng[$mrk_cnt] = $obj->long;
    $begin[$mrk_cnt] = $obj->begin;
    $end[$mrk_cnt] = $obj->end;
    $distance[$mrk_cnt] = $obj->distance;
    $marker_type[$mrk_cnt] = $obj->type;
    $icon[$mrk_cnt]=(($marker_type[$mrk_cnt]=='inquirer')? 'red_marker': 'blue_marker');    
$mrk_cnt++;    
}
?>

Further on there's some JavaScript echoed from php: -

<script>
<?php
    for ($lcnt = 0; $lcnt < $mrk_cnt; $lcnt++){ 
        echo "var point$lcnt = new google.maps.LatLng($lat[$lcnt], $lng[$lcnt]);\n";
        echo "var mrktx$lcnt = \"$inf[$lcnt]\";\n";
        echo "var infowindow$lcnt = new google.maps.InfoWindow({ content: mrktx$lcnt });";
        echo "var marker$lcnt = new google.maps.Marker({position: point$lcnt, map: map, icon:" . $icon[$lcnt] . "});\n";
        echo "google.maps.event.addListener(marker$lcnt,'click', function() {infowindow$lcnt.open(map,marker$lcnt);});\n";
        echo "bounds.extend(point$lcnt);\n";    
    }
?>
    map.fitBounds(bounds);
}
</script>

How are the php variables - $lat[], for instance - finding their way into the JavaScript? They are declared in PHP and they are not being concatenated or quoted. It is assumed the JavaScript will know that $lat[$lcnt] will be the $lat[$mkr_cnt] declared in the php above with $lcnt set to =$mkr_cnt.Many thanks.

Answers


The second block of code you gave literally does that, echoes the javascript to your page, javascript is not concerned if it comes from PHP or any other language, by echoing html/javascript code in your script in this case, you are giving information for the javascript that will run under that page, PHP worked only to retrieve the data from the API and then mounted the javascript that will make it work in browser.

Another handy information about single/double quotes in PHP: What is the difference between single-quoted and double-quoted strings in PHP?


Need Your Help

C# Variables to VBScript

c# variables vbscript sap arguments

Using this C# application pick a start and ending date range, that SAP will then use to do its query. I have made an application that passes one argument and it worked like that, but it does not work

How can I limit Q promise concurrency?

javascript node.js concurrency promise q

How do I write a method that limits Q promise concurrency?