While loop hangs when decrement variable is set in PHP - php

the while loop hangs with the decrement variable ($j--) set after the echo command..
$j = 10;
while($j>-10)
{
if($j==0)continue;
echo (10/$j) . "<br>";
$j--;
}
but works well when set before if statement
$j = 10;
while($j>-10)
{
$j--;
if($j==0)continue;
echo (10/$j) . "<br>";
}
Can anyone explain pls?

When $j==0 it skips the rest of the code in the loop because of the continue so it never gets to the $j-- in the first code.
This means that $j will never get below 0 and the loop will never finish.
As in the second code it will always decrements it before the test, it will eventually get to -10.
Try adding
echo $j.PHP_EOL;
as the first line in the loop (assuming you are using the CLI version) to see what is happening.
Another slightly different version of your code can be used to ONLY avoid the echo when $j is 0, instead of doing the continue...
$j = 10;
while($j>-10)
{
if($j != 0) {
echo (10/$j) . "<br>";
}
$j--;
}

Related

PHP: How to loop from 100 to 0 by -2 without letting it go infinitely?

what I am trying to achieve here is to be able to loop from 0 to 100 (100, 98, 96, 94 ...) but has to stop at 0. What is doing right now is it passes 0 and -2 -4 which crashes the server. What am I doing wrong?
for ($i = 100; $i <= 100; $i--){
echo $i--;
echo "<br>";
}
Maybe a little explanation would be useful.
The middle part of the for loop $i <= 100 is what makes it infinite. That expression is checked before each iteration of the loop, and the loop will continue as long as that expression evaluates to true.
Since you set $ito 100 in the first section of the loop, and you're doing nothing except making it smaller, it will always be <= 100, forever.
The loop will work fine just the way you have it written if you change the continuation condition.
for ($i = 100; $i >= 0; $i--){
echo $i--;
echo "<br>";
}
That way it will continue until $i is reduced to less than zero, then $i >= 0 will be false, and the loop will end.
The third argument in for loop is what will be executed at the end of the loop. So:
for ($i = 100; $i >= 0; $i -= 2){
echo "$i<br>";
}
Will do the trick
As you can read here https://secure.php.net/manual/en/control-structures.for.php
At the end of each iteration, expr3 is evaluated (executed).
Alternatively:
<?php
foreach(range(100, 0, -2) as $n) {
echo $n;
}
for ($i = 100; $i >= 0; $i-=1){
echo $i--;
echo "<br>";
}
I figured it out somehow. Has been studying JavaScript for a year; Loop is still confusing to me

For loop isn't running with php post

I'm converting a bash cgi script to php on apache webserver. For whatever reason I have a for loop that doesn't want to execute. I've tried comparing it to other loops I've done in the past and it seems like it should work but nothing shows up on the page in the source code. It's just an empty area. I also put an echo in the code to echo out which number it's on, but those didn't show up either. Anybody see where I'm going wrong?
for($i=$begin; $i>=$end; $i++) {
echo "$i\n";
echo "<td>somedata$i</td></tr><tr>\n";
}
I've already verified the variables begin and end show up by echoing them just before the loop. Once I hit the loop it's not executing that code. Everything after the loop executes fine as well. I'm also not getting any errors in the apache log files, which is what really is frustrating. Any help would be appreciated.
Thanks!
I think that you should replace >= to <=
i supposed that
$begin =5;
$end = 0;
then you should used decrements $i-- with >=
for($i=$begin; $i>=$end; $i--) {
echo "$i\n";
echo "<td>somedata$i</td></tr><tr>\n";
}
if
$begin = 0;
$end = 5;
then you should less than equal to <= with increment $i++
for($i=$begin; $i<=$end; $i++) {
echo "$i\n";
echo "<td>somedata$i</td></tr><tr>\n";
}
I am not sure about the values both the variable have, but you need to change the >= sign to <= so that the loop can go until $i goes up to the $end value.
for($i=$begin; $i<=$end; $i++) {
echo "$i\n";
echo "<td>somedata$i</td></tr><tr>\n";
}
Your code is use incremental for $i and in your logic you use >=$end I think you have to change it to $i
for($i=$begin; $i<$end; $i++) { echo "$i\n"; echo "<td>somedata$i</td></tr><tr>\n";
Change either >= to <= or make it a decrement loop by changing i++ to i-- Both will work.

Double equals in for loop?

Why doesn't the double equals work in a PHP for loop? The following works:
$cnt = 5;
for ($z = 0; $z <= $cnt; $z++) {
echo $z."!<br />";
}
But why doesn't this work?
$cnt = 5;
for ($z = 0; $z == $cnt; $z++) {
echo $z."!<br />";
}
The loop executes only if the condition evaluates to true. At the first iteration, $z == $cnt is false, so the loop never executes.
A common loop strategy is to use a sentinel value:
$cnt = 5;
$stop = $cnt + 1;
for ($z = 0; $z != $stop; $z++) {
. . .
}
Note that the comparison is negative (!= or !==). Using a sentinel is usually unnecessary for numerical loop variables (I wouldn't recommend it for your posted code), but is useful for other situations (e.g., when $stop represents null, an illegal value, etc.). It's particularly helpful when the loop variable changes in a pattern that is not easy to characterize succinctly.
because on the first iteration $z != $cnt, so the loop stops immediately.
Let us look at this from the computer's perspective:
If I am a computer this is what you told me to do:
set $cnt = 5;
set $z = 0;
check if $z equals $cnt
if so do whatever is in the loop, then increment $z
Trouble is, 5 does not equal 0 and never will, so the loop will simply be skipped. If you had $cnt = $z+1 inside the loop this would be an infinite loop.
So, you see, == works just fine, it simply doesn't do what you think it should do.
Hope this helps!
A for loop works by looping until a condition is made false. In the first example the loop will execute until z = 5 after that z will not longer be less than or equal to cnt (z starts at 0 and increments through each loop). In the second example you have $z == $cnt as your condition, and since z = 0 and cnt = 5 the loop will stop automatically because the condition is made false. You can use not equals instead like following:
$cnt = 6;
for ($z = 0; $z != $cnt; $z++) {
echo $z."!<br />";
}
The syntax of for is:
for (<init>; <condition>; <increment>)
The loop tests <condition> before each iteration. If it's true, it executes that iteration; if it's false, the loop terminates.
In your case, since $z == $cnt is false before the first iteration, the loop terminates immediately.
To do what you want, invert the test. You also need to bump the end value up by one, since the original version used <=, not <. Note that in both cases, the loop executes $cnt+1 times, because you start from 0.
for ($z = 0; $z != $cnt+1; $z++)

Run A PHP function only 30% of Time

I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";

If statement getting hung up

I have a while loop that contains an if statement. The while loop works fine but when I run the following if statement for each value passed through the while loop, and the if statement returns true, the script hangs up and I get the 30 second maximum execution time error.
I am not sure if it is creating an infinite loop or what. Can anyone spot the problem?
$size = count($_POST['itemname']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$itemname= $_POST['itemname'][$i];
$id = $_POST["id"][$i];
if(preg_match('/[A-Za-z]/',$itemname)) {
echo("has words");
} else {
//update code here
}
}
You never increment $i, that is what is hanging it up as it will always be < $size
while ($i < $size) { // changed this to >
// define each variable
$itemname= $_POST['itemname'][$i];
$id = $_POST["id"][$i];
$i++; // increment $i
You never increment $i. Try a for loop instead; they're a little more explicit.
You need to increment $i somewhere outside of the if statement.
you never change $i in the while loop
you have to increment $i for each loop or else if its true once it will always pass
add $i++ between the last 2
}
}
so it looks
}
$i++;
}

Categories