How to move a step back in foreach loop? - php

How do i move a step back in a foreach loop?
Say i have something like this:
Do something for the first run. If b == 1, do something again. See code below.
$i = 0;
foreach ($a as $b) {
if ($i == 0) {
//something
}
if ($b == '1') {
$i = 0;
}
$i++;
}
The problem is, when $b == 1, it is setting $i = 0 but not running the instructions inside.
Any better way to overcome this if it's not possible to step back?
Update:
Thanks guys for the response. Sorry i wan't clear when i typed this.
But I'd managed to achieve what i want by putting the loop in a function and do some conditional checks and pass arguments before calling it.

Not sure if this is a typo, but you have if ($i = 0) instead of if ($i == 0). Possibly your problem is there?
Perhaps another option would be just doing:
if ($b == '1') {
// do something?
}
Final option would be to do a regular for loop and decrement the counter if a condition exists:
for ($x = 0; $x < count($thing); $x++) {
if($thing[$x] == '1') {
$x -= 1;
}
}

are you sure that $i is getting set to 0 in the loop, it is quite possible it is always 0 (because that is what it is set to before the loop)

Related

PHP, array count, two foreach combination

I am solving this not understandable script, I even don't know where from to start. Maybe someone will help me.
I got two arrays example:
$a1 = array(1,2,3 ...);
$a2 = array(4,5,6 ...);
what I need is that first array will divide all values by itsel
for this I would like to get script which will work like this (array values can be savet to the same name because will be anyway continue with them, can be new variable, in this example I use new). In the same way variable can be devidet by itself to get 1 but prefer not to. Example of count.
$b1 = array([0]/[1], [0]/[2], [0]/[3], [1]/[0], [1]/[2], [1]/[3], [2]/[0], [2]/[1], [2]/[3], [3]/[0], [3]/[1], [3]/[2]);
$b2 = array( *** The same like $b1 ***);
On the end will go foreach to write values to table, this I solved already
echo "<table><tr>";
foreach($b1 as $key1 => $val1){
foreach($b2 as $key2 =>$val2){
echo "<td>".$key1.$key2."<br/>".val1*val2."</td>";
}
echo "</tr><tr>";
}
echo "</tr></table>"
Anyone can give me a help to this issue?
To do the division of each element is relatively simple. You do it with 2 for loops. The one thing you have to bear in mind, however, is avoiding division by 0. Do you have elements that could be 0? If so, do you want the division result to be 0, or the same as the numerator? the code I show below assumes the latter:
function getDivided($array) {
$length = count($array);
$return = [];
for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < $length; $j++) {
if ($i === $j) continue;
//the following assumes that the values in the array are never < 1 Change this according to your needs
$return[] = $array[$i] / max($array[$j], 1);
//Another option is to use a conditional
$return[] = $array[$j] === 0 ? $array[$i] : $array[$i] / $array[$j];
}
}
return $return;
}
$b1 = getDivided($a1);
$b2 = getDivided($a2);

Foreach into PHP array

I've this these array values :
$cart_item['addons'][0]['price'] = '52';
$cart_item['addons'][1]['price'] = '34';
$cart_item['addons'][2]['price'] = '12';
......
....
I want that each values are at 0 like :
$cart_item['addons'][0]['price'] = '0';
$cart_item['addons'][1]['price'] = '0';
$cart_item['addons'][2]['price'] = '0';
....
...
So I try this code :
for ($i=0; $i > 0 ; $i++) {
$cart_item['addons'][$i]['price'] = '0';
}
But it does not work. Thanks for your help !
Try this simple solution:
$count=count($cart_item['addons']);
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
If your array is big enough, putting count() function inside for loop is being a crazy coconut. It will be much, much slower. Please use the count outside the loop:
$count = count($cart_item['addons'])
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
You have to loop more often to achive this:
foreach($cart_item['addons'] as &$addons {
foreach($addons as &$addon) {
$addon['price'] = 0;
}
}
You can iterate over $cart_item['addons'], like so:
foreach ($cart_item['addons'] AS $key => &$value) {
$value['price'] = 0;
}
(Your code does not get executed, because $i is never changed and so is never > 0)
Also note that you need to use the reference (&$value) when changing the array in foreach loop.
There are three parts to your for loop: for(counter | test | action){}. It might be useful for you to look at this guide about for loops. You initialise your variable:
$i = 0;
then you do a logical check (the test part):
$i > 0;
If we substitute the the variable ($i) for the value it holds (0) we get:
0 > 0
which will never be true and thus you will never get to the final part (action) of the for loop:
$i++;
Instead you could make it loop until it has moved through your entire array like this:
$elementCount = count(cart_item['addons']);
for($i=0; $i < $elementCount; $i++){
$cart_item['addons'][$i]['price'] = '0';
}
Each time it loops we add one to $i until we reach the stopping condition where $i is no longer less than the number of items in the array.
It's also worth noting that PHP has a number of functions that help working with arrays.

Variable does not change its value

I have been trying to analyze it for like hours now but I can't understand what was wrong with my code :(
$d = 1; //I declare this variable as 1
$a = 0;
while($d<$arraycount-2){
while ($a < 40){
$c = 0;
$b = 0;
while($c < $fc){
$finaloutput = $finaloutput.$database_returned_data[$d][$c].","; //But here, in this loop $d is always 1
$c++;
}
while($b < 5){
$finaloutput = $finaloutput.$mydata[$a][$b].",";
$b++;
}
$finaloutput = $finaloutput."--END--";
$a++;
}
$d++; //But it increments successfully. Hence, the while loop terminates after it meets the criteria.
}
The variable $d is always 1 inside the other loop but it increments outside the loop. Note there is a while statement inside the while. Is there anything wrong?
I'm using $d for my array:
$finaloutput = $finaloutput.$database_returned_data[$d][$c].",";
I am a noob poster. Feel free to ask for more details :)
You don't set $a here:
while($d<$arraycount-2){
while ($a < 40){
So on every iteration besides the first this while condition won't run.
just change it to:
while($d<$arraycount-2){
$a = 0;
while ($a < 40){

These Loops are Not Working Properly

I have been working with the same loop for a couple days now, and it still won't work the way I want it to. I have tried both for, foreach and while and it still refuses to work.
The code that won't work is simply:
if(!empty($_POST['submit'])){
$d = count($_POST['deleteT']);
for ($pi = 1; $pi <= $d; $pi++) {
echo "Banned ".$_POST['deleteT'][$pi]."</br>";
}
}
If deleteT has two values: 'Bob' and 'Joe' it will print:
Banned Joe
Banned
Does anyone have any insight into why this is going on?
Start your loop index with $pi = 0; and only loop while $pi < $d.
I think one of your problems is in your count statement, then with the <= condition in the for loop.
If you use count(), then just use <. Example:
$c = count($my_array);
for ($i = 0; $i < $c; $i++) {
// do stuff
}
That said, an easier way to iterate over an array is with foreach. Like this:
foreach ($my_array as $key => $val) {
// do stuff with $val or $key
}

PHP "for" loop issue

Simple question:
Why is this:
for($k=1;$k<=10;$k+2) { }
giving an infinite loop? When I change $k+2 by $k++, it works fine.
How can I correct it? (I can't change the 10 for an impair number because I need this function to work either with a pair or impair value at that place)
$k+2
This won't change $k's value, so it never get's higher than 10. Probably you meant:
$k+=2
Which will increase $k by two each time the expression get's evaluated (at the end of each for-loop).
for($k=1;$k<=10; $k = $k+2) { }
or
for($k=1;$k<=10; $k += 2) { }
it is infinite loop because $k is not updated, try this instead
for($k = 1; $k <= 10; $k = $k + 2) {}
or
for($k = 1; $k <= 10; $k += 2) {}
Reference: PHP operators

Categories