Divide a number up to 0 in PHP - php

What i am trying to do is divide a number by 2 get the whole number and store the remainder in another variable which i did, but the number should stop dividing until the result gets to 0
Example:
75 / 2 = 37
37 / 2 = 18
.
.
.
.
1 / 2 = 0
This is what i have to far
$num = 75;
$n = (int) ($num / 2); //Get the whole number
$r = $num % 2; //Get the remainder
echo $n . "<br>" . $r;
I know i have to use a loop but i am still new to this so i need help.

Please try something like this:
<?php
$num = 75;
$divNum = 2;
while($num > 0){
$newNumber = (int) ($num / $divNum); //Get the whole number
$remainder = $num % $divNum; //Get the remainder
$num = $newNumber;
echo $newNumber . " " . $remainder."<br>" ;
}
?>
Output Look like this :
37 1
18 1
9 0
4 1
2 0
1 0
0 1

Related

Print 2 items of array per line and separate by comma [duplicate]

This question already has answers here:
Modulus in a PHP loop
(7 answers)
Closed 8 months ago.
can u please help me on this. I have an array with 6 items, I want to print 2 items per line separated by commas, I have this code:
$rates[] = array("2020-01-01"=>3000);
$rates[] = array("2020-01-02"=>3010);
$rates[] = array("2020-01-03"=>3020);
$rates[] = array("2020-01-04"=>3021);
$rates[] = array("2020-01-05"=>3030);
$rates[] = array("2020-01-06"=>3035);
$rates_count = count($rates);
$total = $rates_count;
$col = 2;
for ($i = 0; $i < $total; $i++) {
$date = key($rates[$i]);
$value = end($rates[$i]);
if ($i % $col != 0) {
echo "{$date},";
echo "{$value},";
} else {
echo "{$date},";
echo "{$value}";
echo "</br>";
}
}
This code print this:
2020-01-01,3000
2020-01-02,3010,2020-01-03,3020
2020-01-04,3021,2020-01-05,3030
2020-01-06,3035,
I want this:
2020-01-01,3000,2020-01-02,3010
2020-01-03,3020,2020-01-04,3021
2020-01-05,3030,2020-01-06,3035
Where is the error? Thanks for any help.
I tested this and your output should be correct now
if ($i % $col == 0) {
echo "{$date},";
echo "{$value},";
} else {
echo "{$date},";
echo "{$value}";
echo "</br>";
}
Output:
2020-01-01,3000,2020-01-02,3010
2020-01-03,3020,2020-01-04,3021
2020-01-05,3030,2020-01-06,3035
I changed the comparison to be " == 0"
The first value in the iteration will be cero because 0 % 2 = 0
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
5 % 2 = 1
... and so on
The condition was returing false in the first iteration, it was fixed by changing the comparison of the remainder to be equal to cero.

Round to 5 and 9 php

I'm looking for a formula to round a value to nearest 5 or 9 if the val is less than 5 make 5 if is bigger than 5 make 9.
Example:
$RoundToFive = ceil('232' / 5) * 5;
echo floor($RoundToFive * 2 ) / 2; //Result is 235 Is good
$RoundToNine = ceil('236' / 5) * 5;
echo floor($RoundToNine * 2 ) / 2; //Result is 240 but i need 239
Is there a way to extract always the last 2 digits and convert to 5 or nine ?
Any help is appreciated !
how about:
function funnyRound($number){
$rounded = ceil($number / 5) * 5;
return $rounded%10?$rounded:$rounded-1;
}
This is working
<?php
function roundToDigits($num, $suffix, $type = 'floor') {
$pow = pow(10, floor(log($suffix, 10) + 1));
return $type(($num - $suffix) / $pow) * $pow + $suffix;
};
$RoundToNine = ceil('236' / 5) * 5;
echo roundToDigits($RoundToNine,5);
echo roundToDigits($RoundToNine,9);
You can use any number as $suffix to round to it.
other way, working with strings... :
<?php
function round59($NUMB){
//cast the value to be Int
$NUMB = intval($NUMB);
//Get last number
$last_number = intval(substr($NUMB, -1));
$ROUND_NUMBER = 5;
if($last_number<=5)
$ROUND_NUMBER = 5;
else
$ROUND_NUMBER = 9;
//Remove Last Character
$NUMB = substr($NUMB, 0, -1);
// now concat the results
return intval($NUMB."".$ROUND_NUMBER) ;
}
echo round59(232);
echo round59(236);
?>

What makes this work?

I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
echo '<img src="',$thumbnail_image,'" />';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}
I understand how everything with the exception of this line works.
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
I know it is getting its value from this line:
$images_per_row = 3;
But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.
Any answers at all would be appreciative!
$index % $images_per_row == 0
The % means "mod", example 4 mod 2 = 0.
A % B = the remainder when we divide A by B.
In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.
Hope it helps!
% is the modulo operator. It divides the two numbers and then returns the remainder after the division.
It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.
So, if we make 5 % 2 into a fraction and reduce it:
5 1 (this is the remainder)
--- → 2 ---
2 2
So, 5 % 2 = 1.
If we take 8 % 3 we can do the same thing:
8 2 (this is the remainder)
--- → 2 ---
3 3
So, 8 % 3 = 2.
If there is no remainder, such as in 9 % 3 then you will get 0 back. See:
9 0 (this is the remainder)
--- → 3 ---
3 3
You can write some PHP to see what the values are when doing the modulo operations:
$perRow = 3;
for ($i = 0; $i < 10; $i++) {
echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "\n";
}
Output:
0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3

How to write a loop that generates range intervals in PHP?

I'm newbie here. I want to ask about for loops in PHP.
How to write code that will output this:
i =1;
j = 0-20;
then if i=2; j = 20-40,
i=3; j=40-60,
and so on.
Notes: j is range data from 0-(+20);
I have no idea how to start.
i = 1; range = 0-20;
i = 2; range = 20-40;
i = 3; range = 40-60;
...
You wrote the pattern yourself: "range data from 0-(+20)". You have 3 variables there, i and range defined by min and max. You need to take some time thinking how each of these will change based on how i will change. Then it shouldn't be hard to come up with something like this:
$rangeSize = 20;
for ($i = 0; $i < 10; ++$i) {
$rangeMin = $i * $rangeSize;
$rangeMax = $rangeMin + $rangeSize;
echo "$i : $rangeMin - $rangeMax" . PHP_EOL;
}
output:
0 : 0 - 20
1 : 20 - 40
2 : 40 - 60
3 : 60 - 80
4 : 80 - 100
5 : 100 - 120
6 : 120 - 140
7 : 140 - 160
8 : 160 - 180
9 : 180 - 200
Should be something along those lines
refer to http://www.w3schools.com/php/php_looping_for.asp for the official documentation
<?php
$max_i = put the maximum value for i here
for ($i = 0; $i <= $max_i; $i++)
{
echo "i = $i <br>";
echo "j = $i*20 - 20 <br>";
}
?>

Generate a combination of numbers

I have a PHP page with two variables: $nbRank and $nbNumeric. Depending of these two variables, I want to generate an array containing all combinations existing. For example:
If $nbRank = 3 and $nbNumeric = 2 I would have:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
So, I create different loop and formulas to get the final result, but it doesn't works. This is what I did :
$result = array();
$nbIntRank = 0;
$nbIntNumeric = 0;
$nbRank = array();
$nbNumeric = array();
$nb_rangs = 3;
$nb_chiffres = 2;
for ($i = 1; $i <= $nb_rangs; $i++){
$nbRank[$i] = 0;
}
$nbIntRank = count($nbRank);
for ($i = 0; $i <= $nb_chiffres; $i++){
$nbNumeric[$i] = $i;
}
$nbIntNumeric = count($nbNumeric);
$algo = ($nb_rangs * ($nb_chiffres + 1)) * ($nb_rangs * ($nb_chiffres + 1));
$nbLine = $algo / ($nb_rangs);
$occ = 0;
for ($i = 0; $i < $nbLine; $i++){
foreach ($nbRank as $nbrItem => $nbrValue){
$result[$i][] = $nbrValue;
$occ++;
}
}
echo '#############<br />';
echo '### DATAS ###<br />';
echo '#############<br /><br />';
echo '- Nb Elements : '.$algo.'<br />';
echo '- Nb Lines : '.$nbLine.'<br />';
echo '- Nb Valuable Occurency : '.$occ.'<br />';
echo '<br /><hr /><br />';
echo '##############<br />';
echo '### PARSER ###<br />';
echo '##############<br /><br />';
echo '<pre>';
var_dump($result);
echo '</pre>';
I managed to create my final array with empty values (81 values, in 27 lines of 3 elements) but it only contains 0.
You indicated you'll be fine with pseudo-code.. Sorry I cannot offer specific correction for your php code [if these answers appear - they might be more educating], but I'd chose a recursive solution for this problem.
In each level of the recursion, try all possibilities, and call the same function to find all combinations of one smaller size.
Pseudo-Code:
findCombinations(range,size,sol,resultList):
if (size ==0): #base clause
resultList.append(copy(sol)) #making a copy of sol and appending it as a solution
return
for each i in (0,range):
sol.append(i)
findCombinations(range,size-1,sol,resultList) #recursive invokation, with smaller size
sol.deleteLast() #clean up environment before next calls
Invoke with findCombinations(3,3,[],resultList) where [] is just empty list, and resultList will hold the list of combination when the algorithm is done. this invokation will get all combinations of size 3 with elemenets 0,1,2.
Complexity note:
The number of possibilities is growing exponentially [O(rangesize)], so if you try to invoke it with 20,20 for instance - it might take some [very long] time, for any solution.
$nbRank = 3;
$nbNumeric = 2;
foreach (range(0, base_convert(str_pad('', $nbRank, $nbNumeric), $nbNumeric+1, 10)) as $i) {
echo str_pad(base_convert($i, 10, $nbNumeric+1), 3, 0, STR_PAD_LEFT) . PHP_EOL;
}
Simple idea: What you want is every number from 0 to X with base $nbNumeric, thus we just convert the maximum number to base 10, iterate over it with the common 10-based operators, and convert it back to base $nbNumeric again.
Probably more readable, but in fact exactly the same
$nbRank = 3;
$nbNumeric = 2;
// Top is "base_convert(222, 3, 10);" and therefore the upper limit
$top = base_convert(str_pad('', $nbRank, $nbNumeric), $nbNumeric+1, 10);
for ($i = 0; $i <= $top; $i++) {
echo str_pad(base_convert($i, 10, $nbNumeric+1), 3, 0, STR_PAD_LEFT) . PHP_EOL;
}
Here's a recursive solution:
$nbRank = 3;
$nbNumeric = 2;
function getCombinations ($length, $min, $max, $aStartingCombinations)
{
if ($length == 1)
{
return range ($min, $max);
}
$final = array ();
foreach (getCombinations ($length - 1, $min, $max, $aStartingCombinations) as $combination)
{
for ($i = $min; $i <= $max; $i++)
{
$final [] = $combination . $i;
}
}
return $final;
}
print_r (getCombinations ($nbRank, 0, $nbNumeric, array ()));

Categories