I have a question in PHP that I can not solv开发者_如何学JAVAe.
I have a variable that has the value 5000. I need to divide that variable with a value of 300. For example:
$var = ceil (5000 / 300);
That will result in 17. I need to generate groups of 300 and discover the rest. For example:
$var1 = 300;
$var2 = 300;
.
.
.
$varX = 200; //rest
The number 5000 and 300 are dynamic, so I can not do it manually.
Does anyone know how I could do this?
Just use the modulus operator to get the remainder of a division operation:
$x = 5000;
$y = 300;
$varX = $x % $y; // $varX = 200
If you want the remainder, use the mod operator, %
. E.g. 5000 % 300 = 200.
You're probably look for the modulo operator, which is often but not always %
:
python:
>>> 1500 / 200 ; 1500 % 200
7
100
ruby:
irb(main):002:0> puts 1500 / 200 ; puts 1500 % 200
7
100
erlang:
1> 1500 div 200.
7
2> 1500 rem 200.
100
php:
echo (5 % 3)."\n"; // prints 2
are you looking todo something like this (loop 5000x then put in db when loop hits 300)
<?php
for($i=0;$i<5000;$i++){
$x = $i;
$y = 300;
$varX = $x % $y;
if($varX==299){echo 'Put In db<br>';}
}
?>
I'm not exactly sure what you want, but it seems like you might want an array, coupled with use of the mod operator.
$varX = 5000;
$varY = 300;
$varQuotient = (int)($varX / $varY);
Fill $varQuotient
elements of an array with $varY
. That will get you your groups of 300. The last element of the array will be $varX % $varY
(unless it is 0, in which case it is omitted since $varY
divides $varX
). Is that the type of thing you were looking for?
If you insist on using a loop, it can be done this way:
$x=5000;
$y=300;
while($x % $y !=0) {
// do anything you need here...
$x-=$y;
}
// $x finally contains the rest
精彩评论