condition not working in nested loop in php - php

for ($x = 0; $x <= 3; $x++) {
for ($y = 0; $y <= 4; $y++) {
if ($y == 0) {
mysql_query("insert into tb_weight_rate_management
(nation,zone_id,rate) values ('Domestic',1,'$del_100')");
}
}
}
hello i am little troubled using for loop....in the code above i have two loops ...1st loop will work 3 times and the the inside loop will work 4 times....
now when i click on submit button then it checks loop one and then enter second loop and inserts data 4 times in the database....which is wrong...i want if $y=0;
then it should insert data only once but it is inserting data 4 times can anyone please correct the above condition

You should use == instead of =. Like this:
if ($y == 0) {

the first loop runs 4 times, hence 4 inserts
In the inner loop you declare $y = 0 on every iteration of the outer loop

for each x iteration, there are one time y=0. and since x executes 4 times (0, 1, 2 and 3) y gets 0 value 4 times as well. if you want to do the insertion only once then you must add x value as well like if($y == 0 and x == 0).

Related

How to keep looping in while loop?

I have a table with five rows for example, and my while loop will display the five rows for me as per normal.
I‘m trying to get the loop to keep looping records until let's say $count = 12. I want to start the counter at 0 and it will end at 12. So, I pretty much want the loop to keep showing the same records randomly until it shows me 12 or so results and then stops.
Simple as while ($a != 12)
$counter = 0;
while ($counter != 12) {
// Do stuff
$counter = rand(0, 24);
}

Using number_format in a loop

I am running a for loop 10 times in order to populate data in a data table. In doing this, I wanted to use number_format in order to format the numbers. However, when I apply the number_format the For loop for some reason runs one additional time.
It works just fine when I exclude the number_format. Can anyone explain why this happens?
<?php
foreach($data['data'] as $result) {
For ($n = 0; $n <= 10; $n++){
echo "<td>";
echo number_format($result[$n], 0, ".", ",");
echo "</td>";
}
}
?>
TL;DR: Your loop will always run an additional time. Assuming that there are no errors in your number_format function call, all you have to do to get this to run 10 times is change your code to for($n = 0; $n < 10; n++). Note the use of < and not <=.
For loops are really just syntactical sugar for while loops. The statement for(initial_statement; bound_condition; loop_statement) { code; } is equivalent to
initial_statement;
while(bound_condition) {
code;
loop_statement;
}
Which, functionally, is equivalent to
initial_statement;
while(true) {
code;
loop_statement;
if(!bound_condition) break;
}
This means that if you want a loop to run, say, 2 times, and you write for($i = 0; $i <= 2; $i++) your code will loop as follows:
$i = 0
i++; (i now equals 1)
i <= 2 (condition is true, so continue)
$i = 1
i++; (i now equals 2)
i <= 2 (condition is true, so continue)
$i = 2
i++; (i now equals 3)
i <= 2 (condition is FALSE, so break)
Using the <= operator when your control variable starts at 0 causes an extra iteration to occur, since there are three integer values of i such that 0 <= i <= 2 (0, 1, and 2). To ensure that there are only two iterations, use the < operator, and now the loop will only be executed for values in the domain 0 <= i < 2 (0 and 1).
If you are still bent on using the <= operator and are fine with a non-zero-based iteration count, then you can simply change the initial value of i to 1 to offset the error.
By the way your code is written, I assume that you wish for your inner loop to run 10 times, not 11. This would explain why you are getting an extra iteration, and the issue is quite unrelated to the use of number_format. If you are only getting 10 iterations when you don't use that function, you might want to make sure that the statement 1 == 1 evaluates to true in your PHP interpreter.
Additionally, as a code styling issue, I would recommend using consistent case in your statements; you write foreach (lowercase) but also use For (uppercase). The convention is to use lowercase for both.
I have no clue why you would be only getting 10 iterations without number_format. You might be counting incorrectly? Try changing it to < and see if that resolves your issue.

Execute every 10 rows

I need help. I need a loop that can execute some codes every 10 rows.
Suppose this is the scenario:
$rows = 15; // The row is for a generated report. I need to put a Thick Border, Horizontally every 10 rows.
This is the loop, and inside it I want another loop or any idea how can I execute some command every 10 rows assuming $row = 15, obviously the command should be executed once since the rows is only 15 and command will execute every 10 rows. Thanks everyone :)
$rows = 15;
for($c=0;$c<$size3;$c++)
{
//Location I want to execute a command every 10 rows.
}
Try for loop for this
for($i = 1;$i <= 40;$i++) {
if($i % 10 == 0) {
// your horizontal code here
} else {
// non horizontal code here
}
}
Edit Remember start the loop from 1 not from 0. See codepad
With 0
With 1
seems there is problem in $rows value, insted of adding condition on $rows %10 ==0 you may try setting one counter $i in loop which will get increment for each row and then you can try adding condition on $i %10 ==0
$startrow = 10 //10 if base 1 or 9 if base 0
$endrow = 15 //you said 15 so lets go with this
for($row = $startrow; $row < $endrow; $row+=10)
{
//do your thing here
}
Since you only want to perform the action once every 10 rows, why not start at row 10, then go by increments of 10 instead of incrementing the row 1 by 1.
This should be more efficient since there will be no wasted loops given your circumstance, it also eliminates the need for checking if the row is divisible by 10.

How to use % (modulus) in PHP to pick out every 1st, 2nd and 3rd result?

I am using a PHP while loop in order to get data from a database. Ignoring the data that I'm retrieving from the database and concentrating on the amount of records I have fetched, which is 4.
I want to be able to take the 1st record and insert it into a div called "div1" and take the 2nd record and insert it into a div called "div2", take the 3rd record and insert it into a div called "div3".
When it comes to the 4th record I would like to insert it in to the div called "div1" and so on.
I've managed to get every 3rd result, so skipping the 1st and 2nd record and being able to do it with the 3rd using a snippet from the below code:
if ($i % 3 < 2) {
I'm having trouble adapting that to do what I want it to do.
What you want is some variation of
$targetDivNumber = ($i % 3) + 1;
See it in action.
Try something like (pseudo code)
if ($i % 3 = 0) {put in div1}
if ($i % 3 = 1) {put in div2}
if ($i % 3 = 2) {put in div3}
With below code you can do this too:
$cont = 1;
while( fetch results from query )
{
if($cont == 1)
put in div 1;
else if($cont == 2)
put in div 2;
else if($cont == 3)
put in div3;
$cont = $cont <= 3 ? $cont += 1 : 1;
}

php if iterator divisible by statement for dynamic columns

Im trying to make dynamic column list that will be 4 columns total (PHP). Im echoing an array and after every time 4 array items are echod, I would like to wrap those 4 array items in a div called "column".
So basically, I thought I could do this with a self counting $i++ statement, but first off I'm having trouble starting the count from anything but zero (I tried setting the variable initially outside of the for each loop.)
Anyways, ya, if you could kindly show me how to check to see if the $++ is divisible by 4 in php, so that I can insert a if $i++ is divisible by 4 then echo "" , it would be much appreciated. But first I believe I need to figure out how to start the counting at 1 (so that the if $i++ is divisible by 4 would work... right??)
If you divide by 4 it will be integer division and the quotient will be the factor of 4. What you probably want is the modulus operator %. It will give you the remainder. So when $i is a multiple of 4 it will be 0.
if (($i % 4) == 0) {
// evenly divisible by 4 logic
}
Modulus can be inefficient. Since you are dividing by a multiple of 2, you could shift bits right by 2. It is the same as dividing by 4 and much more efficient. Check out bit shifting.
% is the modulus operator. It returns the remainder after a division, so 7 % 4 == 3.
You really should start from 0. This is because 0 % 4 == 0 and 4 % 4 == 0... AND you want the very first item to be a new row! So you want new rows on 0, 4, 8, etc... If you start at one, then 1, 2, and 3 would not be in a row.
Additionally, we have to remember to close the row on every item one before a new row.
Finally, if we exit our loop without closing the final row, we have to do that after we have exited the loop.
I'll show how to do this with tables, but you can use divs with classes just as easilly.
<table>
<?php
// Start at zero, so we start with a new row
// Since we start at 0, we have to use < number of items, not <=
for ($i = 0; $i < $numberOfItems; ++$i)
{
// if divisible by 0 start new row
if ($i % 4 == 0)
echo '<tr>';
// Always print out the current item
echo '<td>' . $item[$i] . '</td>';
// If the next $i is divisible by 4, we have to close the row
if ($i % 4 == 3)
echo '</tr>';
}
// If we didn't end on a row close, make sure to close the row
if ($i % 4 != 3)
echo '</tr>';
?>
</table>
Modulus!
$a % $b Remainder of $a divided by $b.
http://php.net/manual/en/language.operators.arithmetic.php

Categories