PHP Division results automatically rounded up number - php

i have a simple division
$order = 14 / 10; // 1
$order = 15 / 10; // 2
result automatically convert into round figure
how can i get result like
$order = 14 / 10; // 1.4
$order = 15 / 10; // 1.5
here my actual code $quantity
if (($quantity > 0.99) && ($pro_Type== "BHRF")) {
$pro_Id = $pro_Id -10;
$quantity = $quantity/10;
for ($i=1; $i <11; $i++) {
$pro_Id = $pro_Id +10;
$insert0 = mysql_query("INSERT INTO myorders1 (Product_Id,Quantity,Product_Type,Store_Id,Order_Date,Order_Time)
VALUES ('$pro_Id','$quantity','$pro_Type','$store_Id','$o_Date','$o_Time')", $connection);
}
}

Unless i'm drunk; 14/10 can't be 1 without any rounding involved
echo 14 / 10; // 1.4 as expected
Most probably your database field, Quantity, is integer and doesnt store the fraction and you assume the real number came from division.
Fiddle

Related

PHP Making a variable increment based on another variable's value without having too much code?

i'm trying to increase a variable value depending on the other variable value for example:
i have a variable called $totalhousesleft...
i want to set a price depending on how many $totalhousesleft i have...
everytime the totalhousesleft is down by 10, i want to increase the variable $currentprice by 1.
the starting value of $totalhouses left is 8000 and every time it goes down by 10, i set the $currentprice +1... the starting value of current price is 9...
something like:
If ($totalhousesleft >= 8000) {$currentprice = 9; $sellingprice = 8;}
If ($totalhousesleft >= 7990) {$currentprice = 10; $sellingprice = 9;}
If ($totalhousesleft >= 7980) {$currentprice = 11; $sellingprice = 10;}
If ($totalhousesleft >= 7970) {$currentprice = 12; $sellingprice = 11;}
ALL THE WAY DOWN UNTIL HOUSES LEFT IS 1. If someone can please show me a loop or a shorter code i would really appreciate it!
#elias-soares answer is close, but is missing ceil...and an explanation.
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
$currentprice = 9 + ((ceil(800 - ((min(8000, $totalhousesleft)) / 10))) * 1);
$sellingprice = $currentprice - 1;
}
Try it here: https://onlinephp.io/c/68196
Let's break down how to get $currentprice:
//$currentprice = ceil(9 + (800 - (min(8000, $totalhousesleft) / 10)));
// get the lesser of 8000, or $totalhousesleft
// in other words, 8000 is the maximum number to calculate
$totalhousesleft = min(8000, $totalhousesleft);
// divide total houses left into number of tenth units
$tenth = $totalhousesleft / 10;
// since the price increases when the number of tenth units decreases,
// the unit factor is the difference between the max possible tenths
// and tenths of the current total houses left
$tenthunit = 800 - $tenth;
// tenth unit is fractional for values not evenly divisible by 10,
// so round up
$tenthroundup = ceil($tenthunit);
// multiply the number of tenth units with the price per unit
$pricepertenth = $tenthroundup * 1; // 1 currency per tenth unit
// add the price per tenth cost to the base cost (9 currency)
$currentprice = 9 + $pricepertenth;
Bonus: this can be implemented in a function:
function getPrices ($totalhousesleft, $baseprice = 9, $discount = 1, $priceperunit = 1, $maxtotal = 8000, $units = 10) {
$currentprice = $baseprice + ((ceil(($maxtotal / $units) - ((min($maxtotal, $totalhousesleft)) / $units))) * $priceperunit);
return [$currentprice, $currentprice - $discount];
}
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
list($currentprice, $sellingprice) = getPrices($totalhousesleft);
}
Try it here: https://onlinephp.io/c/2672b
A for or while loop could be used for this. I'd use for:
$iteration = 0;
for($x = 8000; $x > 0; $x = $x - 10){
if(empty($iteration)) {
$iteration = $x/1000;
}
if ($totalhousesleft >= $x) {
$currentprice = $iteration;
$sellingprice = $currentprice + 1;
break;
}
$iteration++;
}
if(empty($currentprice)){
$currentprice = $iteration;
$sellingprice = $currentprice + 1;
}
This iterates over until a match is found then breaks out of the looping. The prices are based on the iteration it is in.
Demo link: https://3v4l.org/Mm432 (updated for edge cases 0-9)
You can use Math.
$currentprice = 9 + (800 - (min(8000,$totalhousesleft)/10));
$sellingprice = $currentprice - 1;

PHP Increment value by 150 if number is 1 to 2

I'm building a shipping website
I want to increment the value depending on the number of items.
Example
default fee is 150
if numItem 1 to 2 = 150,
if numItem 3 to 4 = 300,
if numItem 5 to 6 = 450,
if numItem 7 to 8 = 600,
if numItem 9 to 10 = 750,
and So on every additional 2 items it adds 150 for the shipping fee
I have this PHP code but it didn't work
<?php
$fee = 150;
for($i = 0;$i<$numOrders;$i++) {
if($numOrders % 2 == 0) {
$res = $numOrders / 2;
$shippingFee = $fee * $res;
}
if($numOrders % 2 == 1) {
$res = $numOrders / 2;
$shippingFee = $res;
}
$shippingFee = $numOrders * $i;
}
?>
thank you
You can use the ceil() function to get a whole number after dividing by 2. Simply multiply this against 150:
$numItem = 7;
echo ceil($numItem / 2) * 150;
So, just writing this code should help:
The ceil() method increases the number to be whole (ceiling).
$numItem = 5;
$shippingAmount = (ceil($numItem / 2)) * 150;
You can just do a int division and then multiply by 150:
$amount = ceil($numItem/2)*150;

Filter negative and positive values out of one variable in PHP

I have a variable in PHP where values from a database are inserted. It’s about money. I need to summarize all negative and positives values separately.
Example:
February, I have:
+ 10
− 10
+100
− 50
− 15
+ 70
+ 80
—
Credits added: 260 Euro
Credits paid: −75 Euro
The variable is named $amound in my PHP file. I really have no clue how to do that.
In Excel, this would be as follows: =SUMMEWENN(E1:E48;"<0")
But here I only have a variable, not fields.
Heres some Code:
$reportdata["tableheadings"] = array("Transaktions-ID","Kunde","Datum","Beschreibung","Betrag");
if ($startdate && $enddate) {
$query = "SELECT tblcredit.*,tblclients.firstname,tblclients.lastname FROM tblcredit INNER JOIN tblclients ON tblclients.id=tblcredit.clientid WHERE tblcredit.date BETWEEN '".db_make_safe_human_date($startdate)."' AND '".db_make_safe_human_date($enddate)."'";
$result = full_query($query);
while ($data = mysql_fetch_array($result)) {
$id = $data["id"];
$userid = $data["clientid"];
$clientname = $data["firstname"]." ".$data["lastname"];
$date = fromMySQLDate($data["date"]);
$description = $data["description"];
$amount = $data["amount"];
$currency = getCurrency($userid);
$amount = formatCurrency($amount);
$overallamount += $amount;
// $overallamountout -= $amount;
// $overallamountin += $overallamount > 0;
$reportdata["tablevalues"][] = array($id,''.$clientname.'',$date,nl2br($description),$amount);
}
Indeed, this is very simple (I assume that all of your variables are strings, e.g. coming from a text file, but even if not it will work):
$var1 = '+80';
$var2 = '-30';
$result = (int)$var1 + (int)$var2;
var_dump($result);
Will result in: "int(50)" => Working fine.
You can do it in the DB
SELECT SUM(numbers) AS sum1 FROM pepa WHERE numbers > 0;
SELECT SUM(numbers) AS sum2 FROM pepa WHERE numbers < 0;
Okay,
its done.
Heres the Code which was used:
$summeGesamt = 0;
$summeEingezahlt = 0;
$summeAusgezahlt = 0;
$summeGesamt = $summeGesamt + $data["amount"];
if ( $data["amount"] >= 0) {
$summeEingezahlt += $data["amount"];
} else {
$summeAusgezahlt += $data["amount"];
}

PHP Data Processing Failing With Ambiguous Error

The user requests a Product Category and says what quantity they want of it, ie Sugar 7 lbs.
In the search results, from the database, I have the following items (which are each different products):
Sugar, 8 oz .75
Sugar, 1 lb 1.50
Sugar, 2 lb 4.00
Sugar, 5 lb 7.00
Sugar, 10 lb 11.00
Current process:
Get the search results
Check for the cheapest option for any one of the results (only 10 lbs would meet it) or multiples of one of the results (however many of 1 needed to match the criteria, so 7 X 1 lb)
Put the individual product ids into an array
Get the 1:1 permutations, but within that, use some code to add in up to 3 repeats (because 5 lbs + 2 X 1 lbs is the cheapest option, not 5 lbs + 2 lbs)
In this, check for different quantity unit (oz vs lb) and be able to convert and compare
Compare for cheapest and return cheapest
I'm even disregarding where there are more than 6 elements in the permutation to weed out unlikely options and reduce overhead
This works FINE unless there are > 9 product ids (for some I have > 25), then I get this error in the logs (and a completely unrelated error in the browser): Premature end of script headers
This is a lot of code. I'm sorry, just want to be thorough! Is there a more efficient/effective way?
function processCombos($arr, $qty_search, $qty_unit_search){ //$arr is the dataset, $qty_search is 7, $qty_unit_search is 1 for lbs
$combo=array();
$pid_arr = arrayifyProductIDs($arr);
$count = count($pid_arr);
$members = pow(2,$count);
for ($i = 0; $i < $members; $i++) {
$b = sprintf("%0".$count."b",$i);
$out = array();
for ($j = 0; $j < $count; $j++) {
if ($b{$j} == '1'){
$out[] = $pid_arr[$j];
}
}
$minLength=2;
$out_max = count($out);
if ($out_max >= $minLength) {
// now add in different repeats of each of them
$repeat_max = 3;
$indiv = array();
for($k=0;$k<$out_max;$k++){
$tmp = array();
for ($r = 0; $r < $repeat_max; $r++) $tmp[$r] = array_fill(0, $r + 1, $out[$k]);
$indiv[] = $tmp;
}
$x_ct = count($indiv[0]);
$y_ct = count($indiv[1]);
$z_ct = count($indiv[2]) > 0 ? count($indiv[2]): 0;
$perm = array();
for($x=0;$x<$x_ct;$x++){
for($y=0;$y<$y_ct;$y++){
if($z_ct > 0){
for($z=0;$z<$z_ct;$z++){
$perm = array_merge($indiv[0][$x],$indiv[1][$y],$indiv[2][$z]);
}
}else{
$perm = array_merge($indiv[0][$x],$indiv[1][$y]);
}
$p=0;
$max_p=count($perm);
if($max_p >=7){
}else{
$product_ids = array();
$qty = 0;
$price = 0;
while($p < $max_p){
$product_id = $perm[$p];
$data = $arr[$product_id];
if(!$data['qty_unit_id'] OR !$data['qty']){continue;} // go to the next one if it doens't have qty or qty_unit
if($data['qty_unit_id'] == $qty_unit_search){
$product_ids[] = $product_id;
$qty += $data['qty'];
$price += $data['price'];
}else{
$unit_to_convert_data = getQtyUnitName($qty_unit_search);
$unit_to_convert = $unit_to_convert_data['abbr'];
$unit_to_convert_type = $unit_to_convert_data['conv_file'];
if($unit_to_convert_type == $data['conv_file']){
if($data['conv_file'] == "Mass"){
$product_conv = new PhpUnitsOfMeasure\PhysicalQuantity\Mass($data['qty'], $data['qty_unit']);
}else{
$product_conv = new PhpUnitsOfMeasure\PhysicalQuantity\Volume($data['qty'], $data['qty_unit']);
}
$data['qty_CONV'] = number_format($product_conv->toUnit($unit_to_convert),3,".",",");
$product_ids[] = $product_id;
$qty += $data['qty_CONV'];
$price += $data['price'];
}
}
$p++;
}
if(count($combo)==0 AND $qty >= $qty_search){
$combo = array('product_ids' => $product_ids, 'qty' => $qty, 'price' => $price);
}elseif(($qty >= $qty_search AND $price < $combo['price']) OR
($qty >= $qty_search AND $price == $combo['price'] AND $qty > $combo['qty'])){
$combo = array('product_ids' => $product_ids, 'qty' => $qty, 'price' => $price);
}else{
}
}/// i think it should go here
}
}
}
}
return $combo;
}
Premature end of script headers usually means your script is killed before sending headers to the web server due to a resource limit in RLimitCPU and RLimitMEM directives in the httpd.conf. Either change these directives to allow more CPU and memory to your applications or write more efficient code (3 for loops means processing record^3 times the block inside it. consider rewriting it.)

Find out the nearest bigger multiple of (n) PHP

I have a requirement where users are forced to choose the multiple of (n) quantity of a product.
The (n) value is set with each product that can be any number.
customer can only purchase the quantity of product in the multiple of (n) quantity set with product.
Suppose if (n) is 5 and user entered quantity as 4 and says Add to Cart. I have to add quantity of that product as 5 automatically.
and if user entered 6 as quantity then I have to add the 10 quantity of that product.
How I go about that?
I am not getting what logic should be applied here.
$entered_quantity = 6;
$suppose_n = 5;
$quantity = ceil($entered_quantity / $suppose_n) * $suppose_n;
echo $quantity;
prints 10
that's not php specific;
what you wonna do is to compute.
ceiling(q / n) * n
where q is the user's quantity,
n is the multiplicity
You could try getting the remainder of the number when dividing by the given n
e.g.:
$n = 5;
$amount = 6; // This would be the input, so replace the 6 with a $_POST/$_GET/etc.
$batches = floor($amount / $n);
$rest = $amount % $n;
if ($rest > 0) {
$batches += 1;
// You could give the user feedback here that they didn't put in a full multiple of $n
}
// $batches now contains the right amount of batches, so to get the total:
$total = $batches * $n;
Ofcourse this can be condensed a lot, but this might give a better overview of what happens :).
Try the below function.
function getNextMultipleOfFive($n) {
$tmp=explode('.',($n/5));
if($tmp[1]) {
return ($tmp[0]+1)*5;
}
return $tmp[0]*5;
}
With a do...while loop:
$q = 6; // quantity by user input
$n = 5; // per purchace amount
$i = 0;
if ($q > 0)
{
do
{
$i += $n;
}
while ($i <= $q);
}
echo $i; // 10
Note: not very effective if $q >> $n

Categories