## Posted By

Scooter on 05/09/09

# Fuel consumption

/ Published in: PHP

`<?php    /*    Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.        This work is licensed under the Creative Commons Attribution License. To view    a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or    send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California    94305, USA.    */     /*    NOTE: The "magic numbers" in these functions are from the 2007 Fuel Consumption Guide          published by Natural Resources Canada and use a conversion of 4.546 L = 1 imperial gallon.          U.S. fuel economy ratings use U.S. gallons which are 20% smaller than imperial gallons.    */     // Calculate fuel consumption rating in litres per 100 kilometres    function lph(\$kilometres, \$litres)    {        return (\$litres * 100) / \$kilometres;    }     // Calculate fuel consumption rating in miles per gallon.    function mpg(\$miles, \$gallons)    {        return \$miles / \$gallons;    }     // Convert miles per (imperial) gallon to litres per 100 kilometres.    function lph2mpg(\$mpg)    {        return 282.48 / \$mpg;    }     // Convert litres per 100 kilometres to miles per (imperial) gallon.    function mpg2lph(\$lph)    {        return 282.48 / \$lph;    }     // Calculate fuel consumption in litres.    /*    distanceTravelled = the distance travelled in kilometres; e.g. 20000    percentCity = the percentage of the distance travelled occuring in the city; e.g. 0.55    percentHighway = the percentage of the distance travelled occuring on the highway; e.g. 0.45    ratingCity = city fuel consumption rating in litres per 100 kilometres; e.g. 7.9    ratingHighway = highway fuel consumption rating in litres per 100 kilometres; e.g. 5.9    */    function fuelConsumption(\$distanceTravelled, \$percentCity, \$percentHighway, \$ratingCity, \$ratingHighway)    {        \$cityConsumption = (\$distanceTravelled * \$percentCity * \$ratingCity) / 100;        \$highwayConsumption = (\$distanceTravelled * \$percentHighway * \$ratingHighway) / 100;        \$fuelConsumption = \$cityConsumption + \$highwayConsumption;    }     // Calculate carbon dioxide emissions in kilograms.    function CO2emissions(\$fuelConsumption, \$fuelType)    {        return \$fuelConsumption * ((\$fuelType == 'diesel') ? 2.7 : 2.4);    }?>`