How to start loop from 1 after reaching a variabel assigned number - php

I want to create a loop in php which start again from 1 after reaching a specific number assigned in variable.
Loop has to run 10 time
But after reaching 5 as i++ i want this loop to start again from 1 something as given below.
1,2,3,4,5,1,2,3,4,5
Please help!!

You might want to use the modulo operator, %. This will cause numbers to "cycle" like what you want.
for ($i = 0; $i < 10; $i++) {
echo ($i % 5) + 1;
}
The above will print out the numbers 1 through 5 twice.

Try -
$count = 0;
for ($i = 1 ; $i <= 10; $i++) {
$count++;
echo $count;
if ($count == 5) {
$count = 0;
echo "</br>";
}
}

Try this:
$i=1;
while($i<=10)
{
echo $i;
$i++;
if($i>5)
{
$i=1;
echo "</br>";
}
}

You can try this:-
$count = 10;
for ($i = 0; $i < $count; $i++)
{
if($i != ($count-1)){$coma = ',';}else{$coma = '';}
$value = ($i % 5)+1;
$output = $value.$coma;
echo $output;
}
Output:- 1,2,3,4,5,1,2,3,4,5

<?php
$loop=1;
for($i=1;$i<=10;$i++)
{
echo $loop;
if($i==5)
{
$loop=0;
echo "</br>";
}
$loop++;
}
?>
Output:
12345
12345
This can be achieved without using loop also please find the below 2 functions helpful
First:
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
Second:
$st_date = '2012-07-20';
$ed_date = '2012-07-27';
$dates = range(strtotime($st_date), strtotime($ed_date),86400);
$range_of_dates = array_map("toDate", $dates);
print_r($range_of_dates);
function toDate($x){return date('Y-m-d', $x);}
These 2 functions will be returning you the dates between the 2 dates you will pass and then you can loop on the output array to perform operations

Related

Add all the previous numbers in a for loop to get the current number

I have this for loop:
for($i = 1; $i <= 7; $i++) {
echo $i . "<br>";
}
Which outputs:
1
2
3
4
5
6
7
Now what I want is to add all the previous numbers on each loop. So the output should be:
1
2 // add all above to get this number
3 // add all above to get this number
6 // add all above to get this number
12 // add all above to get this number
24 // add all above to get this number
48 // add all above to get this number
96 // add all above to get this number
...etc
The first and second number doesn't necessarily have to be in the loop, that can be defined manually outside.
What I don't want is to add the value of $i on each loop, but to add all the previous numbers on each loop.
I have tried summing up using this code:
$sum = 0;
for($i = 1; $i <= 5; $i++) {
$sum = $sum + $i;
echo $sum . "<br>";
}
But I get this output:
1
3
6
10
15
21
28
How can I achieve my desired output?
Try this
<?php
$results = [];
for ($i = 0; $i <= 7; $i++){
$currentResult = 0;
if ($i < 2){
$currentResult = $i+1;
}
else{
foreach($results as $currenNumber){
$currentResult += $currenNumber;
}
}
echo $currentResult . '<br>';
$results[] = $currentResult;
}
?>
<?php
$value = 0;
for($i = 1; $i <= 8; $i++) {
if($value < 3){
$value = $value + 1;
} else{
$value = $value * 2;
}
echo $value . '<br>';
}
?>

How to Divide Array list in 3 Parts

<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
foreach($admissions as $key => $row)
{
if(//First Part )
{
echo "Alpha";}
else if(//2nd Part )
{
echo "Beta";
}else
{
echo "Gamma";
}
}
?>
I have a dynamic array list and i want to divide it equally in 3 parts.
if Count of array is 30.
So i want to echo for first 10 record
echo "Alpha";
Second 10 Records
Echo "Beta";
3rd 10 Records
Echo "Gamma";
if array size is 60 then it will be divided into 20 parts each.
How can i echo the alpha, beta and gamma.
I thing your question is about if conditions. So you can use this code:
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$i = 1;
foreach($admissions as $key => $row)
{
if($i > 0 && $i <= $divide)
{
echo "Alpha";
}
else if($i > $divide && $i <= ($divide*2))
{
echo "Beta";
}
else //equal else if($i > $divide*2 )
{
echo "Gamma";
}
$i++;
}
Try using a normal for loop :
For ($i = 0; $i < $count ; $i++){
echo "alpha";
}
For ($i = $count; $i < 2*$count ; $i++){
echo "beta";
}
For ($i = 2*$count; $i < 3*$count ; $i++){
echo "gamma";
}
Try this hope you are expecting this. According to the requirement which you specified in comments.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$range=range(0,12);
$result=array_chunk($range, 4);
if(count($result[count($result)-1])!=4)
{
$temp=$result[count($result)-1];
unset($result[count($result)-1]);
$result[count($result)-1]=array_merge($result[count($result)-1],$temp);
}
print_r($result);
Let's have an array of three elements and play with the modulo:
<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$divisions = array(0 => array(), 1 => array(), 2 => array())
$modulo = 0;
foreach($admissions as $key => $row)
{
$divisions[($modulo + 1) % 3][$key] = $row;
}
This will do the partitioning you need.

Calculate from an array the number that is equal or higher and closest to a given number

I need to calculate from a given array the number that is equal or higher and closest to a given number in PHP. Example:
Number to fetch:
6.85505196
Array to calculate:
3.11350000
4.38350000
4.04610000
3.99410000
2.86135817
0.50000000
Only correct combination should be:
3.99410000 + 2.86135817 = 6.85545817
Can somebody help me? It's been 3 hours I'm getting mad!
UPDATE: I finally finished my code as following:
$arr = array(3.1135, 4.3835, 4.0461, 3.9941, 2.86135817, 0.5);
$fetch = 6.85505196;
$bestsum = get_fee($arr, $fetch);
print($bestsum);
function get_fee($arr, $fetch) {
$bestsum = 999999999;
$combo = array();
$result = array();
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $combo);
}
foreach ($combo as $idx => $arr) {
$sum = 0;
foreach ($arr as $value) {
$result[$idx] += $value;
}
if ($result[$idx] >= $fetch && $result[$idx] < $bestsum) $bestsum = $result[$idx];
}
return $bestsum;
}
function combinations($arr, $level, &$combo, $curr = array()) {
for($j = 0; $j < count($arr); $j++) {
$new = array_merge($curr, array($arr[$j]));
if($level == 1) {
sort($new);
if (!in_array($new, $combo)) {
$combo[] = $new;
}
} else {
combinations($arr, $level - 1, $combo, $new);
}
}
}
I hope the following example might help you. Please try this
<?php
$array = array(
"3.11350000",
"4.38350000",
"4.04610000",
"3.99410000",
"2.86135817",
"0.50000000"
);
echo "<pre>";
print_r($array);// it will print your array
for($i=0; $i<count($array); $i++)
{
$j=$i+1;
for($j;$j<count($array); $j++)
{
$sum = $array[$i] + $array[$j];
// echo $array[$i]. " + ".$array[$j]." = ".$sum."<br>"; //this will display all the combination of sum
if($sum >= 6.85505196 && ($sum <= round(6.85505196)) )//change the condition according to your requirement
{
echo "The correct combinations are:<br/><br/>";
echo "<b>". $array[$i]. " + ".$array[$j]." = ".$sum."<b>";
echo "<br/>";
}
}
echo "<br/>";
}
?>
We will get the result as below
Array
(
[0] => 3.11350000
[1] => 4.38350000
[2] => 4.04610000
[3] => 3.99410000
[4] => 2.86135817
[5] => 0.50000000
)
The correct combinations are:
4.04610000 + 2.86135817 = 6.90745817
3.99410000 + 2.86135817 = 6.85545817
You should do it in two steps:
a. Work out (or look up) an algorithm to do the job.
b. Implement it.
You don't say what you've managed in the three hours you worked on this, so here's a "brute force" (read: dumb) algorithm that will do the job:
Use a variable that will keep your best sum so far. It can start out as zero:
$bestsum = 0;
Try all single numbers, then all sums of two numbers, then all sums of three numbers, etc.: Every time you find a number that meets your criteria and is better than the current $bestsum, set $bestsum to it. Also set a second variable, $summands, to an array of the numbers you used to get this result. (Otherwise you won't know how you got the solution). Whenever you find an even better solution, update both variables.
When you've tried every number combination, your two variables contain the best solution. Print them out.
That's all. It's guaranteed to work correctly, since it tries all possibilities. There are all sorts of details to fill in, but you can get to work and ask here for help with specific tasks if you get stuck.
Thank you all for your help!
My code is working pretty cool when is needed to fetch one or two numbers (addition) only. But can't figure out how to add more combinations up to the total count of elements in my given array.
I mean if there are, let's say, 8 numbers in my array I want to try all possible combinations (additions to each other) as well.
My actual code is:
$bestsum = 1000000;
for ($i = 0; $i < count($txinfo["vout"]); $i++) {
if ($txinfo["vout"][$i]["value"] >= $spent && $txinfo["vout"][$i]["value"] < $bestsum) {
$bestsum = $txinfo["vout"][$i]["value"];
}
}
for($i = 0; $i < count($txinfo["vout"]); $i++) {
$j = $i + 1;
for($j; $j < count($txinfo["vout"]); $j++) {
$sum = $txinfo["vout"][$i]["value"] + $txinfo["vout"][$j]["value"];
if($sum >= $spent && $sum < $bestsum) {
$bestsum = $sum;
}
}
}
$fee = bcsub($bestsum, $spent, 8);
print("Fee: ".$fee);
New updated code.
<?php
$x = 6.85505196;
$num = array(3.1135, 4.3835, 4.0461, 3.9941, 2.86135817, 0.5);
asort($num); //sort the array
$low = $num[0]; // lowest value in the array
$maxpossible = $x+$low; // this is the maximum possible answer, as we require the number that is equal or higher and closest to a given number
$num = array_values($num);
$iterations = $x/$num[0]; // possible combinations loop, to equate to the sum of the given number using the lowest number
$sum=$num;
$newsum = $sum;
$k=count($num);
for($j=0; $j<=$iterations; $j++){
$l = count($sum);
for($i=0; $i<$l; $i++){
$genSum = $sum[$j]+$sum[$i];
if($genSum <= $maxpossible){
$newsum[$k] = $genSum;
$k++;
}
}
$newsum = array_unique($newsum);
$newsum = array_values($newsum);
$k = count($newsum);
$sum = $newsum;
}
asort($newsum);
$newsum = array_values($newsum);
for($i=0; $i<count($newsum); $i++){
if($x<=$newsum[$i]){
echo "\nMaximum Possible Number = ".$newsum[$i];
break;
}
}
?>

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Add static number in the for loop index with PHP

I have following for loop code in PHP
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
}
it will print
10 20 30 40 50
I want to add some specific $i value such as
$i=15 and $i=28
So it shold print
10 15 20 28 30 40 50
How should I edit the code ?
If you want specific values, you should make an array with those values and iterate through it:
$vals = array(10, 15, 20, 28, 30, 40, 50);
foreach ($vals as $i) {
echo $i;
}
if you have fixed place where to show these values .. then you can use simple if
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
if($i == 10)
{
echo '15';
}
if($i == 20)
{
echo '28';
}
}
Ok, i'll play the "interview question" game :
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if ($i === 15 || $i === 28) {
echo $i;
}
}
Result at http://codepad.org/JBPkm8W1
You can improve this answer by adding an "allowed values" table :
$allowed = array (15, 28); // List here all the non % 10 value you want to print
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if (in_array($i, $allowed)) {
echo $i;
}
}
The result at http://codepad.org/w8Erv17K
The easiest way is to use a foreach loop like #WaleedKhan wrote.
To prepare the array you can use for loop like you did:
$vals = array();
for($i = 10; $i <= 50; $i = $i + 10){
$vals[] = $i;
}
$vals[] = 15;
$vals[] = 28;
sort($vals);
foreach(...
Try this :
$extra = array(15,28);
$res = array();
for($i=10; $i<=50; $i=$i+10){
$res[] = $i;
}
$result = array_merge($res,$extra);
sort($result);
echo "<pre>";
print_r($result);
You can put the 15 and 28 values in array and get the values using array_intersect.
Create an array to hold the 15 and 28 values (intermeditate values).
$new_vals = array(15,28);
Now in your for loop you can call array_insersect function to get the intermediate values. Your final code will look like this.
$new_vals = array(15,28);
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
$val_range = range($i,$i+10);
$new_array = array_intersect($new_vals , $val_range);
foreach($new_array as $value)
{
echo $value;
}
}
You could do something like this:
function EchoLoopStuff($start, $to, $step) {
for($i=$start; $i<=$to; $i=$i+$step) {
echo $i;
}
}
But you'd need to add some checking to save yourself from issues when inputs contradict.

Categories