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
Related
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;
I'm currently learning PHP, and I'm struggling with this:
"For every 100 ordered products in a category, 2% will be deducted:"
This is my code:
$gesA = 309; // (The amount of product)
$gesN = 1011.08; // (The full price of product)
$i = 1;
while($i)
{
if($gesA % 100 == 0)
{
echo $gesN;
echo "<br>";
$gesN = $gesN / 0.2;
}
$i++;
$gesN++;
}
echo $gesN;
Yet, I can't figure it out. Could someone help me?
First you find how many times it is that there are 100 ordered products, which can be calculated by divide the number of products by 100.
$no = $getA / 100;
But that can get you a floating number so you remove the decimal part with floor()
$no = floor($getA / 100);
Then the percentage will be 2% times the integer number.
$deductPercentage = 2 * $no;
And the final product price will be the remaining of the deducted price
$deductedPrice = $gesN * $deductPercentage / 100;
$finalPrice = $gesN - $deductedPrice;
I would like to "for loop" through a large number and build an array of items that is x% one way and x% another.
For the sake of exmaple:
I want to generate an array of fake customer records.
The idea is that at the end of the loop, I will have an array that contains 20% users that only contain a customer id and 80% users that contain first name, last name and known details. The generation of the details isn’t important, it’s the percentage that is split in the loop that is.
So far this is what I was working with:
$percentage = $percent_known / 100;
$percnum = $this->number_of_records * $percentage;
$iterat = $this->number_of_records / $percnum;
for ($i=0; $i < $this->number_of_records; $i++) {
if ($i % $iterat == 0) {
//add known records
}
else {
//just add a customer id
}
}
when put 80 as the value of $percent_known I get an iterat of 1.25 and all my records are known.
You can simplify it to fill in all of the known ones ( by filling in up to $percnum) and then add the unknown ones. If you want them to be random, then just use shuffle() at the end to mix the results together...
$percentage = $percent_known / 100;
$percnum = $this->number_of_records * $percentage;
$customers = [];
for ($i=0; $i < $this->number_of_records; $i++) {
if ($i < $percnum) {
//add known records
}
else {
//just add a customer id
}
}
shuffle($customers);
If the values are the same - you can always generate a batch using array_fill() rather than using a loop and merge the two formats and again shuffle the results.
I am creating a shopping cart in PHP and a particular item is buy one get one half price. When the user purchases the item, I would get like the offer to be deducted from the total but I'm stuck on how I would do this mathematically.
So far I have something like this in a if loop getting data from database:
$total = $total+($arraycart['Price']*$quantity);
Then I think it will be something along the lines of:
if ($arraycart['Item'] == "A1" and $quantity > 1) {
//calculate here buy one get one half price
}
Any help appreciated.
<?php
$total = 0;
$arraycart['Price'] = 10;
$arraycart['Item'] = 'A1';
$quantity = 3; // change item quantity here
if ($arraycart['Item'] == "A1" and $quantity % 2 == 0 ) {
//calculate here buy one get one half price
$real = ($quantity/2)*$arraycart['Price'];
$half = ($quantity/2)*($arraycart['Price']/2);
$total = $real+$half;
} else {
$quantity = $quantity-1;
$real = ($quantity/2)*$arraycart['Price'];
$half = ($quantity/2)*($arraycart['Price']/2);
$total = $real+$half+$arraycart['Price'];
}
echo $total;
?>
I wonder if someone could please help me out a little. I have a loop that loops through the contents of a shopping cart. I wish to apply a 25% discount to additional items purchased. So basically 1st item is full price and every other item is reduced by 25%. I've tried various methods but all i seem to get is the discount apply to all or nothing.
The loop below works perfectly if i remove the if statement and its contents thus not wishing to apply a discount. As it currently stands it does not add a discount at all. If i remove the if condition and use it's contents then it will apply a 25% discount to all items.
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
$Total += $ShoppingCart[$Loop][Price];
if($Loop > 1) {
$Total += $ShoppingCart[$Loop][Price];
$PercentageAmount = 25;
$TotalPrice = $TotalPrice * ((100-$PercentageAmount) / 100);
}
}
Edited:
Unfortunately none of the answers, although maybe technically good, do not fix my problem. I have had to result to placing 2 if statements within a loop and then calculating their combined total. Not an ideal solution but works perfectly never the less. Somehow i need the sort it so then the most expensive item is at full price. It would be much easier if i was not tied to using a loop in this fashion and instead could use array functions.
$i = 0;
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
if($i == 0) {
$Total += $ShoppingCart[$Loop][Price];
}
if($i > 0) {
$TotalMulti += $ShoppingCart[$Loop][Price];
$TotalMulti = $TotalMulti * .75;
}
$i++;
}
$NewTotal = $Total + $TotalMulti;
Here's how I would do it:
$prices = array_column($ShoppingCart, 'Price');
array_walk($prices, function(&$price, $i) { if($i) $price *= .75; });
$total = array_sum($prices);
How it works:
The prices are pulled out in their own array -- I much prefer this because the discount code does not mess with the "normal" prices, which might cause unexpected complications.
The array of prices is iterated over, and every element but the first is set to 75% of its value.
The total price is just the sum of the discounted prices.
This code depends on array_column, which is only available starting with PHP 5.5. For earlier versions you can either grab an implementation from here or substitute this:
$prices = array_map(function($el) { return $el['Price']; }, $ShoppingCart);
If the discount percentage is a variable you will also need this modification:
$discount = .25;
array_walk(
$prices,
function(&$price, $i) use($discount) { if($i) $price *= (1 - $discount); }
);
for($Loop = 0; $Loop < count($Cart); $Loop++){
if($Loop > 0) {
$Total += ($Cart[$Loop]['Price']*0.75);
} else {
$Total += $Cart[$Loop]['Price'];
}
}
Hope this helps:
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
# if not first item then discount price
if($Loop > 1) {
$PercentageAmount = 25;
# grab the price
$itemPrice = $ShoppingCart[$Loop][Price];
# what should the user pay?
$itemDiscountPrice = $itemPrice * (100.0 - $PercentageAmount) / 100.0
# add it to total
$Total += $itemDiscountPrice;
} else {
# if first item -> full price
$Total += $ShoppingCart[$Loop][Price];
}
}