Plumbum7
Plumbum7

Reputation: 109

Just a question about str_replace

I have a question about str_replace in PHP. When I do:

$latdir = $latrichting.$Lat;

If (preg_match("/N /", $latdir)) {
    $Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
    $Latcoorl = str_replace ("S ", "-",$latdir);
}

print_r($latdir);
print_r($Latcoorl);

print_r($latdir); gives :N52.2702777778

but print_r ($Latcoorl); gives :N52.270277777800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Yes, it adds a lot of zeros. Can someone explane this behavior just for the fun of it?

print_r ($latrichting);

give's: N

print_r ($Lat);

This give's the weird long number.

So its probably not the str_replace command, you think ?

Upvotes: 0

Views: 228

Answers (5)

Darkerstar
Darkerstar

Reputation: 932

The string operations you did won't generate any 0s. The 0s have to come from $lat. What did you do with $lat? any division by pi? PHP will try to store the most accurate possible float number in $lat. That's not really a problem, its a correct behavior. Just truncate the number when displayed, or round it up.

Upvotes: 0

hlpiii
hlpiii

Reputation: 161

How I would do it; just a variation of Anthony's original answer that keeps everything as numeric and doesn't lapse into string mode.

$Latcoorl = ($latrichting == "N") ? ($Lat) : (-1 * $Lat);

Upvotes: 0

Anthony
Anthony

Reputation: 37065

$latmin2 = bcdiv($latsec, 60, 20);
$latmin_total = $latmin + $latmin2;
$lat = bcdiv($latmin_total, 60, 20);

$latdir = array("N" => 1, "S" => -1);

$latcoorl = $latdir * $latdir[$latrichting];

Happy New Year.

Upvotes: 1

ntd
ntd

Reputation: 7434

On my system this code fragment:

<?php
$latdir = ':N52.2702777778';

If (preg_match("/N /", $latdir)) {
    $Latcoorl = str_replace(" N ", "+",$latdir);
    }
    else {
        $Latcoorl = str_replace ("S ", "-",$latdir);
        }

print_r($latdir);
print_r($Latcoorl);
?>

gives the following result:

:N52.2702777778:N52.2702777778

My best guess is you have something after this code that prints out a serie of 0.

Upvotes: 0

Simon
Simon

Reputation: 37978

Your string replace search string has a space before the 'N' while the dumped value looks like it's N:

Not sure what it has to do with all the zeros though.

Upvotes: 1

Related Questions