Case 1 loop inside another loop Can I assign both the $i variable for incrementing?
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
}
Case 2 : if it's not inside, Could I declare $i for both?
like this
for($i=0; $i < 10; $i++)
{
}
for($i=0; $i < 5; $i++)
{
}
There are already some answers that are just fine, but here's a slightly different perspective.
It depends on what you mean by "can". You can do this in the sense that it is syntactically correct PHP code.
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You will never see this text in your browser.";
}
}
But because a loop does not introduce a new variable scope in PHP, it creates an infinite loop.
The outer loop will execute once, then the inner loop will reset $i to 0, increment it to 5, return control to the outer loop, which will execute once, immediately causing the inner loop to start again, resetting $i to 0 and incrementing it to 5, and so on, forever (at least until your script times out). The outer loop can never end because the inner loop affects $i so that it can never satisfy the exit condition of the outer loop.
In other words, just use a different variable for the inner loop. Removing one integer variable is not going to be a noticeable optimization of your code, if that's what you're concerned about.
In the second example, there's no reason not to reuse $i.
Case 1: It will you get a really odd result, check it out here
How to do it properly? Check that out here
for($i=0; $i < 10; $i++){
for($k=0; $k < 5; $k++){
echo "1)".$i." 2)".$k."\n";
}
echo "\n";
}
Case 2: Works fine as stated in above comments and other answer. But, may I also add that in for instance this example.
for($i=0; $i < 10; $i++){
echo $i."\n";
}
echo "\n Outside the loop: ".$i." \n";
for($i=0; $i < 5; $i++){
echo $i."\n";
}
You can acces $i still after the loop has happend. The reason why you can use $i again is because you are declaring it $i =0; again, without interest toward another loop that is currently running (as is happening in case 1).
You can test this example here
Case 1 : No, you cant. you need to create variable individually for each loop.
for($i=0; $i < 10; $i++)
{
for($j=0; $j < 5; $j++)
{
echo "You are too cute";
}
}
Case 2 : Yes you can.
for($i=0; $i < 10; $i++)
{
echo "You are too cute";
}
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
Case 1:
Short answer No you can't .
Long Answer .
First you need to understand what actually a variable is and How that Loop actually works .
Each and every variably is actually a reference to memory. In you example you have created a variable named $i and it can't be greater or equal 10 after incrementing value by one.
In the machine level it is translated to an address in the memory. say for example $i points to a random address 0xF25 When ever you loop it and incrementing it, the next address becomes 0xF30.
When ever you write a for loop, compiler automatically assigns a fixed memory address and that address it limited to your variable scope.
What compiler does is, it creates a table for that token($i). In simple form Look below an example
$i(This is the token ) -> 0xF25 (This is the value)
This value is updated when you do $i++
In nested Loop compiler assigns same table(though outer loop cant access inner loop variables). If compiler puts same variable for inner loop, it will be contradictory. Because inner loop may start from memory address 0xE21. In that case when your outer loop increment value by One it will be 0xE22 but as discussed above it needs to be 0xF30 .
That is why compiler does not allow this and we need to use CASE 2 example.
Related
I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}
This example has been given as an alternative example (example 4 to be precise) for writing for loops on PHP.net.
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
I understand for loops, I just don’t understand why the variable, $j, is declared in this version of writing a for loop that prints the numbers 1 to 10.
FYI: Removing the variable from the for loop makes absolutely no difference to the result.
I think that it's just here for illustrate the fact that you can use multiple statement with commas.
It's useless here but show an example of the syntax for :
[...] Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. [...]
While it doesn't seem to be necessary in this example. It appears that $j is storing the summation of the iterations:
1+2+3+4+5+6+7+8+9+10 = 55
Which can be useful in some situations. So that would mean this style of looping is for the equivalent of doing several operations on each iteration, such as getting the summation, average, largest value, etc. The point of the example is that you can apply several statements separated by commas.
Explanation
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
for loops takes three part separated by semicolon (;).
Initialize
Compare and test
Increment or Decrements.
Here $i=1, $j=0 is initialization.
$i<=10; is compare and test
$j += $i, print $i, $i++ is increment or decrements part
Now in your increment or decrements part you have three task.
1. is increment $j with last $i
2. print $i
3. increment $i by 1
So in your program $j is not useful. Because it is not taking part of
either print or compare and test.
So the loop is just very simple if you remove $j from every where and write it as
for ($i = 1; $i <= 10; $i++){
print $i;
}
But that $j variable could be used after the loop where from you have taken this code block.
LIKE
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
print $j;
We can remove $j and have the same result:
for ($i = 1; $i <= 10; print $i, $i++);
How are they different? Here's what I'm thinking, but I'm not sure....
If you use pre-incrementation, for example in a for loop with ++j, then you are basically saying: "Make a copy of the value of j for use in the loop, then increment j, then go through the statements in the loop with the copy of j." If you are using post-incrementation in the same loop j++, then you are basically saying: "Make a copy of the value of j for use in the loop, then go through the statements in the loop with the copy of j, then increment j."
The reason I'm unsure is because I've created a for loop that multiplies the value of j by 10 and then outputs the result for j=1 through j=12, using both post- and pre-incrementation. The human readable output is exactly the same with post- and pre-incrementation. I'm thinking, 'How are the outputs exactly the same if there isn't some kind of copy operation involved?'
So, I'm guessing the difference between pre- and post-incrementation truly becomes important, in php, when I use references (which act as pointers in php) rather than names for return values? This would be because copies of references aren't made, so pre-incrementation would be: "Increment j, then go through the statements in the loop with the changed value of j, then increment j again...," whereas post-incremetation would look like: "Use the value of j for the statements in the loop, then change the value of j, then go through the loop with the new value of j..."
Pre- or post-incrementing do not magically delay things until later. It's simply inline shorthand.
// pre-increment
$var = 5;
print(++$var); // increments first, then passes value (now 6) to print()
// post-increment
$var = 5;
print($var++); // passes value (still 5) to print(), then increments
Now let's look at a loop.
for ($i = 0; $i < 9; $i++) {
print($i);
}
The last part of the loop declaration (the $i++) is simply the statement to execute after each time through the loop. It "passes" the value to nowhere, then increments it. $i isn't used anywhere at that time. Later when the next statement is executed (print($i);), the value of $i has already increased.
// add 1, then do nothing with $i
for ($i = 0; $i < 9; ++$i) {}
// do nothing with $i, then add 1
for ($i = 0; $i < 9; $i++) {}
Whichever way you do it, $i will be the same within the loop.
If it helps, you can think of them as small routines that kind of do this:
// ++$i
{
$i = $i + 1;
return $i;
}
// $i++
{
return $i;
$i = $i + 1;
}
As I reread your question, I think the confusion is more with how the loop works than how increment operators work. Keeping in mind that the increment is a straightforward, all-at-once operation, here's how third expression in the loop works.
// here's a basic loop
for ($i = 0; $i < 9; $i++) {
// do loop stuff
print($i);
}
// this is exactly what happens
for ($i = 0; $i < 9; ) {
// do loop stuff
print($i);
$i++;
}
Just because that last line can be put in the loop declaration doesn't give it any special powers. There are no references or anything used behind the scenes. The same $i variable is seen both inside and outside the loop. Every statement inside or outside the loop directly looks up the value of $i when necessary. That's it. No funny business.
When doing $x++, you are post-incrementing... This means that the incrementation will only occur after the statement has been evaluated.
So, given the following code:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
PHP does this:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
// Ignore Post-Increment, Evalutate
$y = $z * $x;
$y = 5 * 10;
// Now Increment x - POST-INCREMENT
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Continue evaluating statement
$y = 5 * 10;
$y = 50;
When doing ++$x, you are pre-incrementing... This means that the incrementation will occur before the statement is evaluated:
$x = 10; $y = 0; $z = 5;
$y = $z * ++$x;
// Do Pre-Increment
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Evaluate
$y = $z * $x;
$y = 5 * 11;
$y = 55;
In the case of a for loop in PHP, PHP evaluates a for loop as follows:
for($i = 0; $i < 30; $i++) {
doSomething();
}
// Is evaluated EXACTLY as such by PHP
$i = 0;
while($i < 30) {
doSomething();
$i++;
}
The first expression ($i = 0) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, $i < 30 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, $i++ is evaluated (executed) as an independent expression.
Therefore, post-incrementing or pre-incrementing a variable as the third expression in the loop doesn't have an effect on the behavior of it. In this simple case, both expressions will behave exactly the same.
However, in a complex loop such as the following:
for($i = $j = 0; $i < 30; $i += ++$j) {
$j = getResult($j);
}
Post-incrementing or pre-incrementing $j directly affects the value of $i according to the examples above. In this case, you need to choose exactly what you want to do.
$i = 0;
echo $i++;
echo $i;
$j=0;
echo ++$j;
echo $j;
Pre increment display incremented value. But Post increment display value then increment. About code will output 01 and 11
Alright, I'm working on a (supposed-to-be) simple counting script using ncurses. Everytime it increments the number, I need it to delete the previous number before adding another number, so that it updates rather than appends.
Here is my code:
<?php
ncurses_init();
$i = 0;
$nStr = "Number: ";
ncurses_addstr($nStr);
ncurses_refresh();
for ($i=0; $i < 100; $i++)
{
$iLen = strlen($i);
for ($j=0; $j < $iLen; $j++)
{
ncurses_delch();
}
ncurses_addstr($i);
ncurses_refresh();
sleep(2);
}
ncurses_end();
?>
Currently when I run it, it outputs like this: Number: 01234[...]
Anyone see where my problem is and how I can fix it?
ncurses_delch() forward-deletes. If you want to move the cusor back one column then output \b instead.
It's a pretty simple question, I always have to go check here and then I hit my head and say it's so obvious. But really after a week of not using it I usually end up writing
for ($i = 1; $i++; $i <= 10;) {
echo $i;
}
some Mnemonic might help
ICE:
Initialisation
Check
Execute
Think logical! The order is the same as the expressions are evaluated.
for ($i = 0; $i < 10; ++$i) {
echo $i;
}
// is same as
$i = 0; // 1.
while ($i < 10) { //2.
echo $i;
++$i; // 3.
}
They go in order.
for (expr1; expr2; expr3)
expr1: Evaluated once at the beginning of the loop
expr2: Evaluated at the beginning of each iteration of the loop
expr3: Evaluated at the end of each iteration of the loop
You want to initialize first, check the condition second, and increment (or decrement) your counter last.
START -> CHECK FOR DANGER -> MOVE AHEAD
for( $i = 0 ; $i < 100 ; $i++ )
Hope it helps :-)
Best of luck!
F
irst (initialisation)
O
Only while (condition)
R
Rolling on (incrementing or decrementing)
I may be daft but don't you want this structure:
for ( $i = 1; $i <= 10; $i++ )
{
echo $i;
}
I don't know of a Mnemonic to remember this structure I've always just seen it as:
STARTING OFF; DO WHILE THIS; PERFORM AFTER EACH ROTATION
Rather:
DEFINE PRIOR TO EXECUTION; DEFINE EXECUTION LIMITS; DEFINE OPERATION FOR EACH ROTATION
Just remember that the guard is always checked before the increment, so you write it before.
If you don't remember the guard is checked before the increment, you're in bigger trouble, because you don't know what the loop will do :p
SAM
Start your engine
Are we there yet?
Move