Get price according distance - php

i am trying to create dynamic price calculation by distance.My requirment similar like this
so I need a function where I can pass
distance and then get price by distance
From 0 -10km = Rs10rs/km (fixed price)
10-15km = rs10Rs/km
15 -20km = 9rs pre/km
20 -30km = 8.5rs per/km
25 -30km = 8rs per/km
30 -40km = 7.5rs per/km
30km -50km above = 7rs / km
foreach ($usersInfo as $index=> $users)
{
$km= 0;
$ridefrom=$users['ride_from'];
$rideto=$users['ride_to'];//this is from lat long
$tempLatLong = explode(',',$users['ride_from']);
$tempLatLong1 = explode(',',$users['ride_to']);
$key = array('lat','long');
$to = array_combine($key,$tempLatLong);
$from = array_combine($key,$tempLatLong1);
$km=distanceCalculation($from['lat'],$from['long'],$to['lat'],$to['long']).'km';
$usersInfo[$index]['distance'] =$km;
$carprice=10;// price will be change dynamical from back end admin can change this.
if($carprice){
$price=$km*10;
}
else{
$price=$km*9;
}
$usersInfo[$index]['price'] =$price;
return $usersInfo;
}

Try something like this:
function price_per_km($distance, $mode) {
if ($mode == 'car') {
switch (true) {
case $distance <= 10:
return 10*$distance;
case $distance <= 15:
return 10*$distance;
case $distance <= 20:
return 9*$distance;
case $distance <= 25:
return 8.5*$distance;
case $distance <= 30:
return 8*$distance;
case $distance <= 40:
return 7.5*$distance;
default:
return 7*$distance;
}
}
else {
// bike
switch (true) {
case $distance <= 10:
return 12*$distance;
case $distance <= 15:
return 11*$distance;
case $distance <= 20:
return 10*$distance;
case $distance <= 25:
return 9*$distance;
default:
return 8*$distance;
}
}
}
echo price_per_km(5, 'car') . "\n";
echo price_per_km(12, 'car') . "\n";
echo price_per_km(25, 'car') . "\n";
echo price_per_km(35, 'car') . "\n";
echo price_per_km(5, 'bike') . "\n";
echo price_per_km(15, 'bike') . "\n";
echo price_per_km(35, 'bike') . "\n";
Output:
50
120
212.5
227.5
60
165
270

Related

Binding parameters in switch statement

I need a little helping hand in my script. As the title suggests it's about parameters. I have this code:
if (isset($_GET['sendit'])) {
$theusersname = $_GET['theusersname'];
$totalmarks = $_GET['totalmarks'];
$mathsobt = $_GET['mathsobt'];
$physicsobt = $_GET['physicsobt'];
$chemistryobt = $_GET['chemistryobt'];
$computerobt = $_GET['computerobt'];
$englishobt = $_GET['englishobt'];
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
$grade = "";
//for grades
switch ($modulo, $grade) {
case 'A-1'://100% ro 80%
if ($modulo >= 79.5 && $modulo <= 100){
$grade = "A-1";
}
break;
case 'A'://79% to 70%
if ($modulo >= 69.5 && $modulo <= 79.4) {
$grade = "A";
}
break;
case 'B'://69 to 60
if ($modulo >= 59.5 && $modulo <= 69.4){
$grade = "B";
}
break;
case 'C'://59 to 50
if ($modulo >= 49.5 && $modulo <= 59.4){
$grade = "C";
}
break;
case 'D'://49 to 40
if ($modulo >= 39.5 && $modulo <= 49.4){
$grade = "D";
}
break;
case 'F'://32 to rest
if ($modulo >= 33 && $modulo <= 39.4){
$grade = "F";
}
default:
if ($modulo >= 0 && $modulo <= 32.9){
$grade = "N/A";
}
break;
}
//for remarks
switch ($grade) {
case '':
break;
default:
break;
}
$query = "INSERT INTO `report`(`name`, `grade`, `total`, `mathsobt`, `physicsobt`, `chemistryobt`, `computerobt`, `englishobt`, `totalobt`, `modulo`, `remarks`) VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt', '$physicsobt', '$chemistryobt', '$computerobt', '$englishobt', '$totalobt', '$modulo', '$remarks')";
$result = mysqli_query($mysqliConn, $query);
// if (mysqli_query($mysqliConn, $query)) {
// echo "New record created successfully";
// } else {
// echo "Error: " . $query . "<br>" . mysqli_error($mysqliConn);
$mysqliConn->close();
// }
The grading switch statement doesn't work. Because I just can't get what parameter I need to give. Same goes for the remarks too. The code may be terrible and don't have sanitization (which in this case I don't need). I'm also a little bit confuse with the strings I passed for cases. I mean does it have an effect on overall?
Thank you.
PS: If there is already a similar answer out there, which i unfortunately i didn't find, i'm ready to view the link. Please post a little explanatory comment.
$modulo && $grade is a boolean expression. Its value is either TRUE or FALSE (and not 'A', 'B' or 'C').
But PHP is a loose-type language and it changes the types of its values as needed before using them. Because of this, 'A' == TRUE and '' == FALSE and your code produces only 'A-1' and 'N/A' grades.
A switch doesn't help here. You should use a sequence of cascaded ifs:
if ($modulo >= 79.5) {
$grade = "A-1";
} elseif ($modulo >= 69.5) {
$grade = "A";
} elseif ($modulo >= 59.5) {
$grade = "B";
} elseif ($modulo >= 49.5) {
$grade = "C";
} elseif ($modulo >= 39.5) {
$grade = "D";
} elseif ($modulo >= 33) {
$grade = "F";
} else {
$grade = "N/A";
}
Read how PHP compare values of different types and read how the switch control structure works.
Here you go
$theusersname = 'theusersname';
$totalmarks = 500;
$mathsobt = 87;
$physicsobt = 82;
$chemistryobt = 75;
$computerobt = 79;
$englishobt = 91;
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
switch ($modulo) {
case $modulo >= 33 && $modulo < 39.5:
$grade = "F";
break;
case $modulo >= 39.5 && $modulo < 49.5:
$grade = "D";
break;
case $modulo >= 49.5 && $modulo < 59.5:
$grade = "C";
break;
case $modulo >= 59.5 && $modulo < 69.5:
$grade = "B";
break;
case $modulo >= 69.5 && $modulo < 79.5:
$grade = "A";
break;
case ($modulo >= 79.5 && $modulo <= 100 ):
$grade = "A-1";
break;
default:
$grade = "N/A";
break;
}
switch ($grade) {
case 'A-1':
$remarks = "You have got A-1 ";
break;
case 'A':
$remarks = "You have got A ";
break;
case 'B':
$remarks = "You have got B ";
break;
case 'C':
$remarks = "You have got C ";
break;
case 'D':
$remarks = "You have got D ";
break;
case 'F':
$remarks = "You have got F ";
break;
default:
$remarks = "You have got nothing";
break;
}
echo $query = "INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt',
'$physicsobt', '$chemistryobt', '$computerobt', '$englishobt',
'$totalobt', '$modulo', '$remarks')";
OUTPUT
INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('theusersname', 'A-1', '500', '87', '82', '75', '79',
'91', '414', '82.8', 'You have got A-1 ')

How to convert the integer values to lacs or crores (Indian numbering system)

I want to convert the integer value to Indian Numbering system. I am giving the value 540000 as input and getting the output value 5.4 Lac, but I want answer 5.40 Lac.
My Code:
<?php
function no_to_words($no)
{
if($no == 0) {
return ' ';
}else {
$n = strlen($no); // 7
switch ($n) {
case 3:
$val = $no/100;
$val = round($val, 2);
$finalval = $val ." Hundred";
break;
case 4:
$val = $no/1000;
$val = round($val, 2);
$finalval = $val ." Thousand";
break;
case 5:
$val = $no/1000;
$val = round($val, 2);
$finalval = $val ." Thousand";
break;
case 6:
$val = $no/100000;
$val = round($val, 2);
$finalval = $val ." Lac";
break;
case 7:
$val = $no/100000;
$val = round($val, 2);
$finalval = $val ." Lac";
break;
case 8:
$val = $no/10000000;
$val = round($val, 2);
$finalval = $val ." Cr";
break;
case 9:
$val = $no/10000000;
$val = round($val, 2);
$finalval = $val ." Cr";
break;
default:
echo "";
}
return $finalval;
}
}
?>
Your problem isn't really this function, since numbers 5.4 and 5.40 are the same number, so either you need to apply formatting here, or in the place where you're using the results. Check the difference of these 2:
echo round(540000/100000, 2);
vs
echo sprintf("%2.2f", round(540000/100000, 2));
The second one will show 2 decimals, since that's defined in the format. You don't really need the round either if you use sprintf, it will round the number to the specified format.
echo sprintf("%2.2f", 555555 / 100000);
this could help what you are expecting.
number_format($val/10000000,2); //for Crore convertion

Number conversion to string (laravel)

I'm new in Laravel and I'm trying to convert a number/amount to string in laravel.
Example:
Number/amount: 1,500
Converted: One Thousand, Five Hundred
How do I suppose to do that? please help thanks
Use PHP NumberFormatter class for conversion :
$digit = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $digit->format(1000);
Output will be:
one thousand
public static function convert_number_to_words($number) {
$hyphen = '-';
$conjunction = ' and ';
$separator = ', ';
$negative = 'negative ';
$decimal = ' point ';
$dictionary = array(
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'thousand',
1000000 => 'million',
1000000000 => 'billion',
1000000000000 => 'trillion',
1000000000000000 => 'quadrillion',
1000000000000000000 => 'quintillion'
);
if (!is_numeric($number)) {
return false;
}
if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
// overflow
trigger_error(
'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
E_USER_WARNING
);
return false;
}
if ($number < 0) {
return $negative . Self::convert_number_to_words(abs($number));
}
$string = $fraction = null;
if (strpos($number, '.') !== false) {
list($number, $fraction) = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $dictionary[$number];
break;
case $number < 100:
$tens = ((int) ($number / 10)) * 10;
$units = $number % 10;
$string = $dictionary[$tens];
if ($units) {
$string .= $hyphen . $dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remainder = $number % 100;
$string = $dictionary[$hundreds] . ' ' . $dictionary[100];
if ($remainder) {
$string .= $conjunction . Self::convert_number_to_words($remainder);
}
break;
default:
$baseUnit = pow(1000, floor(log($number, 1000)));
$numBaseUnits = (int) ($number / $baseUnit);
$remainder = $number % $baseUnit;
$string = Self::convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= Self::convert_number_to_words($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$string .= $decimal;
$words = array();
foreach (str_split((string) $fraction) as $number) {
$words[] = $dictionary[$number];
}
$string .= implode(' ', $words);
}
return $string;
}
You can access the function wherever you want within the program as
Classname::convert_number_to_words(123456789.123);
// one hundred and twenty-three million, four hundred and fifty-six thousand, seven hundred and eighty-nine point one two three
<?php
/**
* English Number Converter - Collection of PHP functions to convert a number
* into English text.
*
* This exact code is licensed under CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* #link http://stackoverflow.com/q/277569/367456
* #question Is there an easy way to convert a number to a word in PHP?
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
* You can use this freely and modify it however you want.
*/
function convertNumber($number)
{
list($integer, $fraction) = explode(".", (string) $number);
$output = "";
if ($integer{0} == "-")
{
$output = "negative ";
$integer = ltrim($integer, "-");
}
else if ($integer{0} == "+")
{
$output = "positive ";
$integer = ltrim($integer, "+");
}
if ($integer{0} == "0")
{
$output .= "zero";
}
else
{
$integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
$group = rtrim(chunk_split($integer, 3, " "), " ");
$groups = explode(" ", $group);
$groups2 = array();
foreach ($groups as $g)
{
$groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});
}
for ($z = 0; $z < count($groups2); $z++)
{
if ($groups2[$z] != "")
{
$output .= $groups2[$z] . convertGroup(11 - $z) . (
$z < 11
&& !array_search('', array_slice($groups2, $z + 1, -1))
&& $groups2[11] != ''
&& $groups[11]{0} == '0'
? " and "
: ", "
);
}
}
$output = rtrim($output, ", ");
}
if ($fraction > 0)
{
$output .= " point";
for ($i = 0; $i < strlen($fraction); $i++)
{
$output .= " " . convertDigit($fraction{$i});
}
}
return $output;
}
function convertGroup($index)
{
switch ($index)
{
case 11:
return " decillion";
case 10:
return " nonillion";
case 9:
return " octillion";
case 8:
return " septillion";
case 7:
return " sextillion";
case 6:
return " quintrillion";
case 5:
return " quadrillion";
case 4:
return " trillion";
case 3:
return " billion";
case 2:
return " million";
case 1:
return " thousand";
case 0:
return "";
}
}
function convertThreeDigit($digit1, $digit2, $digit3)
{
$buffer = "";
if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
{
return "";
}
if ($digit1 != "0")
{
$buffer .= convertDigit($digit1) . " hundred";
if ($digit2 != "0" || $digit3 != "0")
{
$buffer .= " and ";
}
}
if ($digit2 != "0")
{
$buffer .= convertTwoDigit($digit2, $digit3);
}
else if ($digit3 != "0")
{
$buffer .= convertDigit($digit3);
}
return $buffer;
}
function convertTwoDigit($digit1, $digit2)
{
if ($digit2 == "0")
{
switch ($digit1)
{
case "1":
return "ten";
case "2":
return "twenty";
case "3":
return "thirty";
case "4":
return "forty";
case "5":
return "fifty";
case "6":
return "sixty";
case "7":
return "seventy";
case "8":
return "eighty";
case "9":
return "ninety";
}
} else if ($digit1 == "1")
{
switch ($digit2)
{
case "1":
return "eleven";
case "2":
return "twelve";
case "3":
return "thirteen";
case "4":
return "fourteen";
case "5":
return "fifteen";
case "6":
return "sixteen";
case "7":
return "seventeen";
case "8":
return "eighteen";
case "9":
return "nineteen";
}
} else
{
$temp = convertDigit($digit2);
switch ($digit1)
{
case "2":
return "twenty-$temp";
case "3":
return "thirty-$temp";
case "4":
return "forty-$temp";
case "5":
return "fifty-$temp";
case "6":
return "sixty-$temp";
case "7":
return "seventy-$temp";
case "8":
return "eighty-$temp";
case "9":
return "ninety-$temp";
}
}
}
function convertDigit($digit)
{
switch ($digit)
{
case "0":
return "zero";
case "1":
return "one";
case "2":
return "two";
case "3":
return "three";
case "4":
return "four";
case "5":
return "five";
case "6":
return "six";
case "7":
return "seven";
case "8":
return "eight";
case "9":
return "nine";
}
}
Use the PHP built-in NumberFormatter class and Ensure to enable this extension in php.ini by uncommenting this line: extension=php_intl.dll
Read this , there is number class for php.
http://php.net/manual/en/class.numberformatter.php

If&Else stuck on return

(sorry for my bad English writing). I've got a problem where I'm stuck with an if and else system that returns the level that you're.
Everything is good, if you have 20 clicks it will tell you that you're level 2, if you have 550 clicks it will tell you're level 6. But when you go up to 1500 clicks it needs to say level 9, but it will still say level 8.
My code:
$levelown = 'Level 1';
function ifElse() {
global $levelown;
global $arrayIP;
if($arrayIP['clicks'] >= 0 && $arrayIP['clicks'] <= 49)
{
$levelown = 'Level 2';
}
/* .... More if and elses with levels */
// This is the problem, this will keep telling me that I'm level 8.
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($score['clicks']/1000)+8);
}
and you are <strong><?php echo $levelown; ?></strong>
Thank you for helping!
The problem that i saw from your current code is that you have
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($score['clicks']/1000)+8);
}
which i think should be
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($arrayIP['clicks']/1000)+8);
}
since $score['clicks'] isn't present you will always end up with level 8
It's probably easier and more readable to make it a switch/case statement like so:
$highscore = $mysqli->query("SELECT id,name,clicks,ip,factory FROM highscore ORDER BY clicks DESC LIMIT 0,50 ");
$ipquery = $mysqli->query("SELECT id,name,clicks,ip,factory FROM highscore WHERE ip = '".$_SERVER['REMOTE_ADDR']."'");
$arrayIP = $ipquery->fetch_array();
$levelown = 1;
function ifElse() {
global $levelown;
global $arrayIP;
switch (true) {
case $arrayIP['click'] > 3000:
$levelown = floor(($arrayIP['click']/1000)+8);
break;
case $arrayIP['click']== 3000:
$levelown = 11;
break;
case $arrayIP['click'] >= 2000:
$levelown = 10;
break;
case $arrayIP['click'] >= 1500:
$levelown = 9;
break;
case $arrayIP['click'] >= 1000:
$levelown = 8;
break;
case $arrayIP['click'] >= 750:
$levelown = 7;
break;
case $arrayIP['click'] >= 500:
$levelown = 6;
break;
case $arrayIP['click'] >= 350:
$levelown = 5;
break;
case $arrayIP['click'] >= 200:
$levelown = 4;
break;
case $arrayIP['click'] >= 50:
$levelown = 3;
break;
case $arrayIP['click'] >= 0:
$levelown = 2;
break;
}
$levelown = "Level " . $levelown;
}

MySQL Select Not Returning resource

I am having a small problem with my PHP MySQL Select. The function is inside of a PHP class. Here is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
integer given in C:\xampp\htdocs\include\database.php on line 59
Warning: extract() expects parameter 1 to be array, null given in
C:\xampp\htdocs\include\database.php on line 59
The function just simply updates the database to show what browser and OS they visited the site with. The function is called from another file that is called by an AJAX call that uses POST to send the data about the OS and browser that was gathered from a Javascript file. It only fails if there is an entry of the IP address already in the database. If there is no IP Address entry in the database it succeeds in creating one.
Here is my code:
function addStat($browser, $os){
$IE = 0; $Firefox = 0; $Safari = 0; $Opera = 0; $Chrome = 0; $otherb = 0;
$Windows = 0; $Linux = 0; $Mac = 0; $Android = 0; $iOS = 0; $otheros = 0;
$ql = 0; $totalVisits = 0;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$q1 = mysql_query("SELECT * FROM " . DB_STATS . " WHERE ip='$ip'", $this->connection);
if (mysql_num_rows($q1)==0){
$browser = mysql_real_escape_string($browser);
$os = mysql_real_escape_string($os);
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$q = $this->query("INSERT INTO " . DB_STATS . " VALUES (null, '$ip', '$Chrome', '$IE', '$Firefox', '$Opera', '$Safari', '$otherb', '$Windows', '$Mac', '$Linux', '$Android' , '$iOS' , '$otheros', 1)");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else if (mysql_num_rows($q1)==1){
extract(mysql_fetch_array($ql));
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$totalVisits += 1;
$q = $this->query("UPDATE " . DB_STATS . " set Chrome='$Chrome', IE='$IE', Firefox='$Firefox', Opera='$Opera', Safari='$Safari', otherb='$otherb', Windows='$Windows', Mac='$Mac', Linux='$Linux', Android='$Android' , iOS='$iOS' , otheros='$otheros', totalVisits='$totalVisits'");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else{
return(-1);
}
}
I hope everything made sense and that someone will help.
I see it now -- you used $ql (lower case L) when you intend to use $q1. Let this be a lesson against using very short variable names or very similar names.
// $ql was initialized to 0
$ql = 0; $totalVisits = 0;
// $q1 holds the result resource
extract(mysql_fetch_array($q1));
It is not advisable to call extract() on the output of mysql_fetch_array() unless you also specify the second parameter MYSQL_ASSOC as the fetch type. By default it returns both numeric and associative indices for each column.
extract(mysql_fetch_array($q1, MYSQL_ASSOC));
// Or better
extract(mysql_fetch_assoc($q1));
In general, I would probably advise against using extract() in most any situation, since it results in numerous variables dumped into the global namespace, in particular when you have done SELECT * without being specific about which columns are selected. Better to access them via their array:
$row = mysql_fetch_assoc($q1);
echo $row['browser'];

Categories