I'm trying to make a select list of prices in my system. The prices are stored as integers. I'm able to get the lowest price and highest price but I want to display them in a select list. I don't want the select list to increment slowly but by 100 or 10,000 or, 100,000 depending on what my starting number is what where i'm at in my incrementation.
For example, say I have these 2 prices:
500000
12345689
I'm trying to increment them by 100,000 Then when I get to 1,000,000 I want to increment by that. It will look something like this:
500000
600000
700000
800000
900000
1000000
2000000
I'm using a custom function and a bit of formatting to get all my prices and get my start price and end price:
$prices = my_custom_function(); // Pulls All Prices in a random order
if(!empty($prices)){
sort($prices); // Sort Prices Lowest to Highest
$price_low = $prices[0];
$price_high = $prices[count($prices)-1];
$price_start = intval( $price_low[0].str_repeat( '0', strlen( $price_low ) - 1 ) );
$price_end = intval( ( $price_high[0] + 1 ).str_repeat( '0', strlen( $price_high ) -1 ) );
}
Using the same example above, my start price and end price will be:
$price_start = 500000
$price_end = 20000000
Now it's at the loop where I run into trouble incrementing it by the values I want. I'm trying to use a while loop and determine where I am in my incrementer:
<?php $i = $price_start; $x = 0; while($x < 10) : ?>
<option value="<?php echo $i; ?>"><?php echo format_price($i); ?></option>
<?php
if(1000 % $i == 0)
$i+=1000;
else if(10000 % $i == 0)
$i+=10000;
else if(100000 % $i == 0)
$i+=100000;
else if(1000000 % $i == 0)
$i+=1000000;
else
$i+=10000000;
$x++;
endwhile;
?>
I ended up adding in the x variable because I kept running into infinite loop problems but theoretically it should be while($i <= $price_end). Can somebody point me in the right direction on how to get the expected output please? I feel like I'm close but not quite there yet and there's probably a better / faster way to go about it. Any help would be great.
I guess a simplified way of looking at it is:
1 -> +1
10 -> +10
100 -> +100
1000 -> +1000
10000 -> +10000
and so forth.
Get power of 10: log10(1234); // 3.09131
Round down: floor(log10(1234)); // 3
Re-raise as power of 10: pow(10,floor(log10(1234))); // 1000
???
Profit.
If someone needs the full solution here it is:
$price = 100; // Starting Price
$priceEnd = 10000; // Ending Price
while($price <= $priceEnd) {
echo $price . "<br/>";
$increase = pow(10,floor(log10($price)));
$price = $price + $increase;
}
Related
I don't understand for loop in PHP,
`$total = 0;
for ($i = 1; $i <= 10; $i++) {
$total += $i;
}
echo $total;`
normally equal an 11 no ? he output me 55, but for python when you execute similar code with "while loop"
total = 0
while total <= 10:
total+=1
print(total)
output me 11
please someone can help me?
Your PHP and python code is not equivalent. In python you just add 1 each time in the loop. However in the PHP you are adding the value to the $i value, which of course keeps increasing every time - i.e. 1+2+3+3+5...etc.
You could write
$total += 1;
or just
$total++;
instead and it would work the same as the python. But then again that makes $total redundant because it just has the same value as $i, and you don't really need two variables doing the same job.
Or you could write a while loop to be more directly equivalent to the python:
$total = 0;
while ($total <=10) {
$total++;
}
echo $total;
PHP CODE
In the PHP code, you get the sum of 1 to 10 numbers using for loop.
That is,
0+1+2+3+4+5+6+7+8+9+10 = 55
Because you have initially given 0 to the $total variable in the PHP code. Then you have given 1 to the $i variable in the for loop and you keep increasing the loop 1 by 1 until the value in $i is less than 10 or equal 10. Then the value in $i is added to the value in the $total.
1st Iteration
$total = total + 1
2nd Iteration
$total = total + 2
3rd Iteration
$total = total + 3
.
.
.
.
.
10th Iteration(because $i <= 10)
$total = total + 10
Then exit the loop and now $total = 55
PYTHON CODE
In the python code you have also using while loop and 0 is assigned to the total variable at the beginning of the code.
In this case all you have to do is increase the value of the total variable by 1
That is,
1st Iteration
total = total + 1
2nd Iteration
total = total + 1
3rd Iteration
total = total + 1
.
.
.
.
.
10th Iteration(because total <= 10)
total = total + 1
Then exit the while loop and now total = 11
These two codes are not the same!!!
Simply because in php code you are incrementing it with i as:total+i
if total wore intially zero 0+1+2+3+4+5+6+7+8+9+10==55
while in python you are incrementing it with total+1 not i
so each time only +1 incrementaion
so 0+1+1+1+1+1+1+1+1+1+1=11
I tried asking this earlier, but I don't think I phrased the question correctly so I worked out something that got me the result I was after and now am hoping that it will help someone help me.
Problem: I have 10 items. If you buy 1, it's $10. I will sell you the second one for $9. I will sell you the third item for $8. I will keep taking off money until we get to $5/item because that is the lowest I will sell it for. So, if you buy all 10, it will cost you $65.
This is the pricing model I am trying to achieve, except at a much larger scale. Instead of a handful of items using dollars, I'm talking about up to millions and using fractions of pennies.
This is my current code:
<?php
function getCost($num_items)
{
$min_price = 0.002;
$max_price = 0.007;
$discount_range = 1000000;
$discount_per_additional_item = ($max_price - $min_price) / ($discount_range - 1);
$price_per_unit = MAX($min_price, ($max_price - ($num_items - 1) * $discount_per_additional_item) );
return $price_per_unit;
}
$array = [100, 1000, 10000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000];
foreach ($array as $value)
{
$sum = 0;
for ($i = 0; $i < $value; ++$i)
$sum += getCost($i);
echo number_format($value) . ' | $' . number_format($sum) . "\n";
}
Which results in:
100 | $1
1,000 | $7
10,000 | $70
100,000 | $675
200,000 | $1,300
300,000 | $1,875
400,000 | $2,400
500,000 | $2,875
600,000 | $3,300
700,000 | $3,675
800,000 | $4,000
900,000 | $4,275
1,000,000 | $4,500
I'm using $array as a sanity check where in the real world, I would simply calculate for the actual number the customer is being charged for.
My question is: Is there a way to accomplish this without using a for loop? Something, perhaps, more elegant?
I made an example online: http://sandbox.onlinephpfunctions.com/code/47e270dbad8cbe16c9ea906ffd2dce098a52fbca
This code will have the same output, and does not have the inner loop:
$min_price = 0.002;
$max_price = 0.007;
$discount_range = 1000000;
$discount_per_additional_item = ($max_price - $min_price)/($discount_range - 1);
$num_progressively_discounted_items =
ceil(($max_price - $min_price) / $discount_per_additional_item);
foreach ($array as $value) {
$num_items_above_min = min($value, $num_progressively_discounted_items);
$num_items_at_min = $value - $num_items_above_min;
$sum = $num_items_at_min * $min_price +
$num_items_above_min * $max_price -
$discount_per_additional_item
* $num_items_above_min * ($num_items_above_min - 1)/2;
echo number_format($value) . ' | $' . number_format($sum) . "\n";
}
This is what it does:
It first checks how many times the unit discount can be subtracted from the original price before hitting the minimum price. If more than the number of items you are buying, then this calculated figure is corrected to that number of items.
The remaining number of items (if any) are also taken note of: these will all have the minimum price.
The sum consists of two parts. The easy part is represented by the number of items that will go for the minimum price, and it is a simple multiplication.
The second part of the sum consists of an always decreasing term, or otherwise put: it is the maximum price for the number of items that don't go for the minimum price, minus the sum of 0+1+2+3+4+5...+n. For that the formula is known: n(n-1)/2.
Like I mentioned in comments, there is something strange in your code: for $i=0 the value returned by getCost($i) is higher than the max price, as the unit discount gets added to it. This can be corrected by starting your inner loop with $i=1. Anyway, this means there is a tiny difference in the result of my proposed code, as it does not have this peculiarity. But as the discount per unit is so tiny, you don't actually notice it in the printed output.
You can do this a little bit more functional style:
function sumOfNaturalSeries($n)
{
return ((1 + $n) / 2) * $n;
}
$minPrice = 0.002;
$maxPrice = 0.007;
$discountRange = 1000000;
$discountStep = ($maxPrice - $minPrice) / $discountRange;
$getPrice = function ($numberOfItems) use (
$minPrice,
$maxPrice,
$discountRange,
$discountStep
) {
if ($numberOfItems <= $discountRange) {
return $maxPrice * $numberOfItems - sumOfNaturalSeries($numberOfItems - 1) * $discountStep;
}
$itemsAboveRange = $numberOfItems - $discountRange;
return $maxPrice * $discountRange - sumOfNaturalSeries($discountRange - 1) * $discountStep + $minPrice * $itemsAboveRange;
};
$array = [100, 1000, 10000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000];
$sums = array_map($getPrice, $array);
var_dump($sums);
var_dump(array_map('number_format', $sums));
Here is demo.
Take a notice on computational error.
I am trying to build up a script that gets the current percentage of the iteration of a loop.
I have :
<?php
$counter = 0;
$total = 100;
foreach($key as value) {
$counter = $counter + 1;
//looping here
$percentage = $counter/total;
}
In my case outputs within the loop for 5 iterations
0.01
0.02
0.03
0.04
0.05
And I need it to output
20
40
60
80
100
To do something like a current percentage completion.
More random exmaples
For 10 loops should be
10
20
30
40
50
60
70
80
90
100
For 100 loops
1
2
.
.
100
For 6 loops
16.6
//brain damaged
Sorry for the noob math php question but I am in a fog today like no days. Thank you and it's much appreciated.
Firstly, you have to get the total amount of iterations. count() helps in this case.
<?php
$counter = 0;
$total = count($yourArray);
// ...
// inside the loop
$counter++;
$percentage = $counter/$total;
Live example
Converting 0.xx to x % is left as an exercise for the reader.
To calculate percentage, you take the current and divide it by the total, then multiply that value by 100, then round it off. I also take the floor value so that 99.7% doesn't round up to 100 since it's not truly complete yet.
for($i=1;$i<=count($yourArray);$i++) {
$percentage = floor(round( (($i / total) * 100), 1 ));
}
Store the total length of the array in a variable and use that to calculate the percentage. Watch that you prefix your variables with $. Also, you might want to name your variables more appropriately—an array isn't a key.
$counter = 0;
$length = count($array);
foreach ($array as $value) {
$counter++;
$percentage = $counter / $length;
}
You can do exactly what are you asking in this way
$counter = 0;
$length = count($array);
foreach ($array as $value) {
$counter=$counter+1;
for ($stepvvx = 10; $stepvvx <= 100; $stepvvx=$stepvvx+10)
{
if ($counter==intval(($length*$stepvvx)/100)){
echo "<br>$stepvvx %";
}
# do your task here
}
you need to do ($total/$iterations) * $counter like this code:
$counter = 0;
$total = 100;
$iterations = count($key);
foreach($key as value) {
$counter++;
$percentage = (($total/$iterations) * $counter)/100;
}
So i have a foreach and i want to insert a bit of html every say 6 times or maybe 11 times the loop is run.
So my insert on each 13th record
if ($i % 13 == 0) {
}
trouble is i want to add a bit more randomness to it.
Totally forgotten what this is called as well
Something like this will make some code execute $percentage of the time every loop. For example you could set $percent = 20 then your code will execute only 20% of the time each iteration.
$value = rand( 0, 100 ); // Set your ranges (min/max)
$percent = 0; // Set percentage
if ( $percent >= $value )
{
// Will only execute $percentage of the time each loop
}
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