John Detlefs John Detlefs - 4 months ago 8
PHP Question

Can call function twice?

Whenever I run this code I get a:


PHP Fatal error: Cannot redeclare compare_distance()


The temporary solution appears to have been to duplicate
findNearestLocation()
and give it a different name, so instead of calling
findNearestLocation()
twice I call
findNearestLocation1()
and
findNearestLocation2()
.

I've tried unsetting the variables in the foreach loop but I can't quite figure out what I'm missing.

Answer

Of course, man )

Change:

function findNearestLocation($clientLocation) {

    global $depotLocations;
    $findDepot = $depotLocations;
    $count = 0;

    foreach ($findDepot as $row) {

        $currentDepot = array($row['location_latitude'], $row['location_longitude']);
        $findDepot[$count]['distance'] = distance($currentDepot,$clientLocation);
        $count ++;

    }    

    function compare_distance($a, $b) {
        if ($a['distance'] == $b['distance']) return 0;
        return ($a['distance'] < $b['distance']) ? -1 : 1;
    }

    usort($findDepot, 'compare_distance');

    return $findDepot[0];

}

To:

function compare_distance($a, $b) {
    if ($a['distance'] == $b['distance']) return 0;
    return ($a['distance'] < $b['distance']) ? -1 : 1;
}

function findNearestLocation($clientLocation) {

    global $depotLocations;
    $findDepot = $depotLocations;
    $count = 0;

    foreach ($findDepot as $row) {

        $currentDepot = array($row['location_latitude'], $row['location_longitude']);
        $findDepot[$count]['distance'] = distance($currentDepot,$clientLocation);
        $count ++;

    }    

    usort($findDepot, compare_distance);

    return $findDepot[0];

}

Or to (if you are using PHP7):

function findNearestLocation($clientLocation) {

    global $depotLocations;
    $findDepot = $depotLocations;
    $count = 0;

    foreach ($findDepot as $row) {

        $currentDepot = array($row['location_latitude'], $row['location_longitude']);
        $findDepot[$count]['distance'] = distance($currentDepot,$clientLocation);
        $count ++;

    }    

    usort(
        $findDepot, 
        function ($a, $b) {return $a['distance'] <=> $b['distance'];}
    );

    return $findDepot[0];

}

Good luck!

Comments