How to reiterate same loop again in php? - php

I have the following foreach loop, how can I reiterate over the same loop index again?
$n = 0;
$currentTotal = 0;
$currentSettlement = $coupons[0]->settlement_id;
foreach ($coupons as $coupon){
if($currentSettlement == $coupon->settlement_id){
$currentTotal += $coupon->amount;
}else{
$settlements[$n]['total'] = $currentTotal;
$currentTotal = 0;
$currentSettlement = $coupon->settlement_id;
$n++;
// after this I want to reiterate current loop from the beginning
}
}

If you want necessary foreach loop you can use a function which you fix that it runs only twice:
$n = 0;
$currentTotal = 0;
$currentSettlement = $coupons[0]->settlement_id;
for2loop(1,$coupons);
function for2loop($loopagain,$coupons)
{
foreach ($coupons as $coupon) {
if ($currentSettlement == $coupon->settlement_id) {
$currentTotal += $coupon->amount;
} else {
$settlements[$n]['total'] = $currentTotal;
$currentTotal = 0;
$currentSettlement = $coupon->settlement_id;
$n++;
if($loopagain == 1)
for2loop(2,$coupons); // after this I want to reiterate current loop from the beginning
}
}
return $currentSettlement
}
but i think that yu must prefer while loop or for loop better

Related

Printing numers without using PHP inbuild functions

$numbers = array(3,5,6,7,8,11);
$missing = array();
for ($i = 3; $i < 11; $i++) {
if (!in_array($i, $numbers)){
$missing[] = $i;
}
}
I want to find the missing numbers from 3 to 11 without using PHP innuild function, i have tried but i haven't not completed fully.
In this code i have used in_array but without this i have to do. any one help here.I am new to PHP using PHP inbuild i can do this, but this is not my case.
Use foreach loop inside on $numbers and check for the value of $i. Declare a flag variable, say $found to false. While looping inside if we get the number, set $found to true and exit the loop. In the end, if $found still stays as false, add the current $i to the result.
<?php
$numbers = array(3,5,6,7,8,11);
$missing = array();
for ($i = 3; $i <= 11; $i++) {
$found = false;
foreach($numbers as $value){
if($value === $i){
$found = true;
break;
}
}
if(!$found) $missing[] = $i;
}
print_r($missing);
Online Demo
you can use array_diff same as :
$numbersOrigin = range(3, 11);
$numbers = array(3,5,6,7,8,11);
$missing = array_diff($numbersOrigin, $numbers);
unuse buildIn functions :
$numbers = array(3,5,6,7,8,11);
$missing = array();
$index = 0;
for ($i = 3; $i < 11; $i++) {
if ($numbers[$index] === $i) {
$index++;
} else {
$missing[] = $i;
}
}

PHP List All Combination of Elements of Array

I have an array:
$arr=array("A","B","C");
I want to make its all of combination as:
array("A")
array("B")
array("C")
array("A","B")
array("A","C")
array("B","C")
array("A","B","C")
i want to make an process all of this combinations but i don't want generate all combinations, store them in an array and apply function to them. Because this requires a lot of memory with large combinations. I have 40 items for this process (I have long time but i don't have enough memory).
I want to have a function like this:
function ProcessArrayCombinations($array){
foreach($array as $v){
//generate and process next combination of array
print_r($nextcombination);
}
}
Thank you.
This code recognizes the combinations as binary numbers, using the fact that there is a formula which states that the sum of all combinations possible from n elements is 2^n. Knowing its binary logarithm is integer, we can define a model where each possible binary number constructed from n digits is a set of combinations. Code is untested, if there are typos, please, let me know in comments.
function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}
$elementCount = count($status);
$trues = 0;
while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
//for ($i = 0; $i < count($status); $i++) {
// if ($status[$i}) {
// print
// } else {
// don't print
// }
//}
}
}
I edited and used your function as below. Thank you again Lajos.
function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}
$elementCount = count($status);
$trues = 0;
while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
for ($i = 0; $i < count($status); $i++) {
if ($status[$i]) {
echo $array[$i];
}
}
echo '<br/>';
}
}

Reset Counter in While Loop

I would like to reset counter in the following loop. Have no idea how to do it
$j = 1;
while($row = mysqli_fetch_array($check)) {
$value = $row['tmpi'];
$calculate = mysqli_query($link,"SELECT * FROM tmpi_db WHERE tmpi_id = '".value."'");
$action = mysqli_num_rows($calculate);
if($j == $action) {
//RESET $j, $j must be one again, nothing is working I have tried $j = 1;
//It's keep incrementing 1,2,3,4,5,6,7.....
}
}
$j++
Please help
Something like this should work. Simply start at zero, increment it in beginning and reset the $j if the action occurs, the next time it loops the $j will increment again and be in zero configuration (i.e. contain value 1):
$j = 0;
while($row = mysqli_fetch_array($check))
{
$j++;
$value = $row['tmpi'];
$calculate = mysqli_query($link,"SELECT * FROM tmpi_db WHERE tmpi_id = '".value."'");
$action = mysqli_num_rows($calculate);
if($j == $action)
{
$j = 0;
}
}
Just move your $j++ in an else section eg
if($j == $action){
//stuff and reset
}else{
$j++;
}
You can try this
if($j == $action) i{
//your code
$j=0;
} else {
$j++;
}

Getting an undefined offset in my PHP array while in a foreach

I need some help, even though I think I'm checking for the length of the array and I should be breaking out of the loop, I still get warnings on my [else if ($value....] line. So either I'm missing something crucial or I've been staring at this code segment too long and its obvious. Any insight would be appreciated.
$count = count($filter); //Filter is an array
if ($count > 1 ){
//Compare values and generate a range to choose from
$i = 1;
foreach($filter as $value){
//Break the loop if at the end of the array
if ($i >= $count){
//throw new exception($i .' '.$count);
break;
}
//if the value is smaller then the next procceding value, because they are already in order of presidence,
//add it to our range of potentials.
else if($value < $filter[$i]->value){
array_push($range, key($filter));
}
$i++;
}
}else {
return false;
}
I suspect that there are gaps in your array. Try this:
$filter = array_values($filter); // this will remove any gaps in the array
$count = count($filter);
if ($count <= 1)
return false;
for ($i = 0; $i < $count; $i++)
{
if ($i != $count-1 && $filter[$i]->value < $filter[$i+1]->value)
array_push($range, key($filter));
}
Your array might have non-numeric keys. Then try this:
foreach($filter as $key=>$value)
{
// test for $filter[$key];
}
Or your $filter array doesn't hold objects, then you can't use the -> in
$filter[$key]->value
try this code.... no need of checking count..
$range = array();
$i = 1;
foreach($filter as $value)
{
if(isset($filter[$i]) && $value < $filter[$i]->value)
{
array_push($range, key($filter));
$i++;
}
else
{
break;
}
}

Define an index on a new array in a loop?

I have the following code:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if($range_day == $number['date']){
#$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}
This line: $chart_data[$range_day] += 0; was giving me an undefined index error, so I added the isset check, but it's not set so it wrecks my array. I know that it's not set, and I don't care, but I read all over that the # solution is in poor taste. How can I remove the error the correct way?
You could just set it to zero at the beginning:
$chart_data = array();
foreach ($range as $range_day) {
$chart_data[$range_day] = 0;
foreach ($numbers as $number) {
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}
Did you take a look at the array_key_exists function: http://php.net/manual/en/function.array-key-exists.php ?
Something like:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if(!array_key_exists($range_day, $array)) {
$chart_data[$range_day] = 0;
}
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
}
}
}
You can check if it's not set, then set it:
foreach ($numbers as $number) {
if (!isset($chart_data[$range_day])) {
$chart_data[$range_day] = 0;
}
if ($range_day == $number['date']) {
$chart_data[$range_day] += $number['events'];
} else {
$chart_data[$range_day] += 0; // you're just adding 0 so why have this line at all?
}
}
This answers assumes that there is the possibility that $range could contain a duplicate $range_day and so it won't overwrite the corresponding element in $chart_data.

Categories