php task

 for 

range 10-20 kms : price is 20

for range 20-30 kms price is 15;

for range 30-40 kms price is 15;

minimum price is 100


for example he travel 25 kms


100+10*20+10*15+5*15


for this code below


<?php




$carid = 'a';

$distance = 21;

echo getPricePerDistance($carid,$distance);

function getPricePerDistance($carid,$distance){

    $farelist  =[

        ['miles_from'=>0,'miles_to'=>10, 'range' => '10', 'price' => 20],

        ['miles_from'=>10,'miles_to'=>15, 'range' => '5', 'price' => 15],

        ['miles_from'=>15,'miles_to'=>20, 'range' => '5', 'price' => 10],

        ['miles_from'=>20,'miles_to'=>25, 'range' => '5', 'price' => 9],

    ];

  

    $data = $farelist;

    $total_fare = 0;

    $total_distance = array_sum(array_map('intval', array_column($data, 'range')));

    

    if ($total_distance >= $distance) {

        $remaining_distance = $distance;

    

        foreach ($data as $d) {

            if ($remaining_distance > 0) { // Check if there's remaining distance to cover

           

                $range_start = intval($d['miles_from']);

                $range_end = intval($d['miles_to']);

                $distance_in_range = min($range_end - $range_start, $remaining_distance);

    

                $total_fare += $distance_in_range * $d['price']; // Calculate fare for this distance

                $remaining_distance -= $distance_in_range; // Update remaining distance

    

                if ($remaining_distance <= 0) {

                    break; // No more distance to cover, exit the loop

                }

            }

        }

    

        return $total_fare; // Output total fare

    } else {

        return  0; // If total distance is less than the requested distance

    }

}


?>

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...