PHP : Get coordinates latitude/longitude from string
Problem :
Let say we are dealing with another program that produces coordinates (lat/long) in a string format that look like this :
"(142.6278389135, 43.29162915041)"
and we want to assign the float values into variables.
Solution :
Break the string with explode()
function, cast the string values into float with floatval() functions. See codes below :
<?php
$str = "(142.6278389135, 43.29162915041)";
// remove the parentheses
$clean = substr($str, 1, -1);
$coord = explode(', ', $clean);
$long = floatval($coord[0]); // cast string to float
$lat = floatval($coord[1]); // case string to float
echo "Long : ".$long."\r\n";
echo "Lat : ".$lat."\r\n";
?>
Output :
Long : 142.6278389135
Lat : 43.29162915041
Reference :
See also : PHP : Extract part of a string starting from the middle
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20.9k Golang : Force your program to run with root permissions
+20.4k Golang : Get current file path of a file or executable
+10.1k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+8.2k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+3k JavaScript: Add marker function on Google Map
+3.7k Golang : If else example and common mistake
+5.6k Gogland : Single File versus Go Application Run Configurations
+8.9k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+33.2k Golang : Convert []byte to image
+13.2k Golang : Generate universally unique identifier(UUID) example
+11.9k Golang : Get query string value on a POST request
+13.1k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content