I am writing a loop that is building a table. With a mysql_num_row, I get how many persons (18), and I want tables with 6 persons max (so: $Peoples = (mysql_num_row($SQL_statement) /6;).
In the loop, I increment $Count: $Count = $Count + 1;
When I write:
Do{
[code]
} while($Count == $Peoples);
The condition is not working: after 1 loop it exits from the loop. I printed $Count wich is 1, and $Peoples is 3.
Is there something to do with this?
Thanks!
because 1 != 3. You need while($count != $Peoples)
Or better yet, while($count < $peoples)
Do you mean to use
Do{
[code]
} while($Count != $Peoples);
(note the inequality check).
The condition is not working: after 1 loop it exits from the loop. I
printed $Count wich is 1, and $Peoples is 3.
== is the equality operator - it checks if both sides are equal.
Your PHP code is operating correctly - you are telling the code to exit when count is different to people. $Count wich is 1, and $Peoples is 3. meets that criteria. The code I've posted above will continue looping while count is not equal to people.
Maybe you want do { [code] } while($Count < $Peoples) or do { [code] } while($Count != $Peoples). What your program is doing right now is adding 1 to $Count and then checking the loop condition. Since $Count != $Peoples, the loop exits.
== is the equals comparison operator. Your count will never initially equal the number of people, so your loop doesn't loop (do-while loops always execute the initial code in the do section, regardless of whether or not the loop condition is met).
What you likely need is to use the < operator, as you're incrementing your count over the life of the loop.
Related
I am learning PHP. I decided to adapt a solution to the famous FizzBuzz problem from Javascript to PHP, just to see how JS and PHP compare.
For those who forgot what the FizzBuzz problem is :
Write a short program that prints each number from 1 to 100 on a new
line. For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number. For
numbers which are multiples of both 3 and 5, print "FizzBuzz" instead
of the number.
I am using a lot of short-circuit evaluations in the following examples.
Here's the clever solution (not written by me) that I adapted to PHP:
Works great!
Then, for the sake of challenge, I decided to try and rewrite it in one single line.
Here's how I started:
Seems like a good start. My condition in the while loop: if $i is not set set, then I set it to zero, but if it is already set, I skip the first part and check if it's inferior to 100.
As you can see on this picture, my loop works.
Since my goal is to write it in one line, I need to increment $i inside my conditional statement, just as with my previous multi-line solution. But when I write $i++ < 100 as before, something weird happens. My loop only runs once and stops.
Very weird indeed.
Even weirder, if I use both increments (one in the condition and one in the loop), the loop then works fine, and applies both increments.
I'm puzzled. Is it because there is a safeguard for infinite loops somewhere? With all those short-circuit evaluations, even my IDE PHP Storm says 'variable $i is probably undefined'. But it gets defined, and my loop works fine under certain conditions. What did I miss ?
EDIT:
Here's the code:
Multi-line working FizzBuzz:
$i = 0;
while ($i++ < 100) {
$msg = '';
($i % 3) || ($msg = $msg . 'Fizz');
($i % 5) || ($msg = $msg . 'Buzz');
echo $msg . "\n";
}
Weird loop iteration (you can delete the increment either in the loop or in the condition, or leave both to see the different effects):
while ( (!isset($i) && ($i=0 || true) ) || ($i++ < 100) ) {
echo $i . "\n";
$i = $i +1;
}
if $i is not set set, then I set it to zero
This is not quite right. Here's what's going on.
Your statement ($i=0 || true) sets $i to TRUE.
PHP's type juggling with print "1" for "$i". Consider $v = TRUE; echo "$v"; to see this in effect.
On the next iteration, your second condition is evaluated as TRUE < 100 which evaluates to FALSE, thereby exiting the loop.
So, in order to fix your problem, simply drop the || true and be on your merry way.
$i=0 || true results in $i being true.
true++ doesn’t actually do anything.
true < 100 is false.
echo true outputs 1.
An explicit true + 1 creates 2.
OMG, Yes! I thought I needed the || true part because ( !isset($i) && ( $i = 0 ) ) will either do both sides of the &&, or neither. I never thought that ( $i = 0 ) would evaluate to "true". But it looks like it does :)
OBSOLETE COMMENT: I found the origin of the quirk. Not sure why it happens though.
If I rewrite $i++ as ($i = $i + 1), it works fine.
while ( (!isset($i) && ($i=0 || true) ) || (($i = $i + 1) < 100) ) {
echo $i . "\n";
}
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.
My code is:
$count=0;
foreach( $List AS $email){
$data = my_function($url);
$count++;
if(filter_var($email , FILTER_VALIDATE_EMAIL)){
...............
my_function runs a simple cURL for an url and returns session_id and api_identity as results. If I run it in the loop for each email in the list, my code is very slow and takes time to show results.
now
$data = my_function($url);
Is applied for each email.
My question:
Is there any way to apply $data = my_function($url); for every 10th mail in the whole list?
If I'm not misunderstanding your question, you want to do something every nth iteration, which can be accomplished using modulo operators:
$count = 1;
foreach ($List as $email)
{
if ($count % 10 == 0) $data = my_function($url);
$count++;
...
}
If you don't know what x % y does, it simply returns the remainder of the expression x/y. A simple trick is therefore to use the fact that when evaluating x % n for different values x = 1, 2, 3..., the same result will repeat every nth time.
Note that depending on what your counter starts at, you will get a different start-email. If you keep it 0 as you have now, the function will be called for the 1st, 11th, 21st, .... emails. If you change it to 1 as I did, the first email for which the function will be called is the 10th one.
You can use https://stackoverflow.com/a/44883380/7095134 this answer or by using counter variable you can achieve that.
e.g:
counter=0;
for(i=0; i<=100; i++)
{
if(counter==10){ counter=0; call_your_function(); }
else { do the rest of work; counter++ ;}
}
I know this below statement works
for ($i= 0; $i=<10; $i++)
will output till 0 to 10
but when I write this code
for ($i=0; $i=10; $i++)
it print 10 for unlimited times... why why it not print 0 to 10...
what error I have done to get the result 0 to 10 for it....
The middle term in a for loop is the condition that says whether the loop should continue running. i=10 assigns 10 to i, and it also evaluates to the number 10, which is not zero, so it's considered true. Since the loop's condition is always true, it never stops running.
because i=10 always be true i==10 will be good
The second statement in the for loop is the condition. When its not true it will leave the loop. i=10 is not a comparator. i will be set to 10 every round that loop goes and because it "works" its resulting in true. i == 10 would be a comparator but i would never be 10 in its first round.
if $i< or =10 Will perform,if $i> 10 will break,each time $i will +1 you can set the $i begin to value or set the maximum to achieve the result that you want.
" = " sign is an assignment operator and can't be used as conditional where as >= , == , <= such operators are conditional, so while checking for a condition you should not use " = "
please write like this below
for($i=0; $i <= 10; $i++)
{
echo $i;
}
Good afternoon, good people of SO!
I'm trying to make a binary calculator, which adds two binary strings together and returns the result in binary.
However, my loop (used for checking the input consists of 0 or 1) seems to falter and return either a 503 (Service Temporarily Unavilable) or suggests I've hit the maximum execution time (30 secs).
I can't figure out why. It seems to bypass this problem if I change && to ||, however this returns a false positive for a bad input.
Here is the code:
// Spring cleaning - add some variables
$submit = htmlspecialchars(strip_tags(stripslashes($_POST['submit'])));
$val1 = htmlspecialchars(strip_tags(stripslashes($_POST['val1'])));
$val2 = htmlspecialchars(strip_tags(stripslashes($_POST['val2'])));
$val1_length = strlen($val1);
$val2_length = strlen($val1);
$val1 = str_split($val1, 1);
$val2 = str_split($val2, 1);
// Val 1 - Checking
$count = 0; // count variable counts how many times the loop recurs and stops it appropriately
while ($count <= $val1_length) {
if(($val1[$count] != 0) || ($val1[$count] != 1)) { // checks if input is comprised of 0 or 1
showInputError();
exit(); // input does not contain 0 or 1, abort script and do not attempt further calculations
$count = $count + 1; // increment the count variable after one successful loop
}
} // Val1 was fine
Thanks in advance! :)
As bwoebi said in the comments, put the bracket one line higher in the if statement, as you're not actually counting up, so the loop will go on forever if no value is found..
$count = 0; // count variable counts how many times the loop recurs and stops it appropriately
while ($count <= $val1_length) {
if(($val1[$count] != 0) || ($val1[$count] != 1)) { // checks if input is comprised of 0 or 1
showInputError();
exit(); // input does not contain 0 or 1, abort script and do not attempt further calculations
}
$count = $count + 1; // increment the count variable after one successful loop
} // Val1 was fine
Why don't you simply use a simple regex like
$input= '1101010001010101110101';
preg_match('/^[01]+$/', $input);
It seems to me you are not verifying your $val1_length in the while loop. What happens if your POST values are empty? You will get an infinite loop, so you might want to replace the while like this:
while ($count <= $val1_length && !empty($val1_length) {...}