i have following code for loop
for ($i=0; $i<=(count($subusers)-1); ++$i) {
is there a reason to use ++$i instead of $i++ if latter doing same thing?
In a for loop, it doesn't matter since you're not doing anything with the returned value.
However you should still note the difference between ++$i and $i++, which is that $i++ returns $i and ++$i returns $i+1.
For example...
$i=0;
echo $i++; //0
echo ++$i; //2
++$i is a micro-optimisation, it executes fractionally faster than $i++. However, unless the $subusers array is being changed within the loop so that count($subusers) can change from one iteration to the next, then any slight positive gain in speed is being negated (and then some) by counting the number of array entries every iteration.
Note that $i++ and ++$i would both execute at the end of each iteration of the loop. It isn't the same as initialising $i to 1 rather than to 0.
In this case there is no difference because you are in a loop.
I would suggest you read up a bit on post and pre incrementation since it is always one of the favorite questions in interviews ^^
if you do i++, the value of i is first used then incremented
if you do ++i, i is incremented then used
for example
int i = 0;
while (aBool){
print (i++);
}
will show 0,1,2,3,4,...
as
int i = 0;
while (aBool){
print (++i);
}
will show 1,2,3,4,5,...
No, in this case it is only stylistic. Maybe someone just wanted to use a pre-increment operator for once.
++$i make php execution fast and also increment the thing on the same line of code.
this link may helpful:- http://ilia.ws/archives/12-PHP-Optimization-Tricks.html
Related
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.
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;
}
This question already has answers here:
Pre-incrementation vs. post-incrementation
(3 answers)
Closed 8 years ago.
I have checked for loop these two ways, but given same output:
1: Increment use ++$i
for($i=0; $i<10; ++$i){
echo $i;
}
2: Increment use $i++
for($i=0; $i<10; $i++){
echo $i;
}
These both code gave this output:
0 1 2 3 4 5 6 7 8 9
We learn ++$i mean pre increment, $i++ mean post increment,
why that post and pre increment not work? can someone please explain me? thank you.
Value of $i++ and ++$i will be same after evaluation.
As $i++ first evaluate value of $i then increment $i.
And
++$i first increment then evaluate value of $i.
Here in for loop, it follows step
initialization
test condition(if true then execute body/else exit)
increment/decrement
As again its working for a new line, either you use $i++ or ++$i it will be the same.
But if you use it in between the for loop you can see the difference.
Check Link for more details
for example
$i++; // Or ++$i;
echo $i;
It will give same value in both condition.
But if you use echo $i++; or echo ++$i then you will find difference.
Pre- and post- incrementing only make a difference when there are other operations happening in the same statement. For example:
$i = 0;
echo ++$i;
Will return 1, as opposed to this:
$i = 0;
echo $i++;
Which will return 0. In the latter case, the increment happens after the echo.
In your original example, the entire statement being executed is either ++$i or $i++. Either way, the order doesn't matter because nothing else is happening.
I know the more efficient way to have a loop over array is a foreach, or to store count in a variable to avoid to call it multiple times.
But I am curious if PHP have some kind of "caching" stuff like:
for ($i=0; $i<count($myarray); $i++) { /* ... */ }
Does it have something similar and I am missing it, or it does not have anything and you should code:
$count=count($myarray);
for ($i=0; $i<$count; $i++) { /* ... */ }
PHP does exactly what you tell it to. The length of the array may change inside the loop, so it may be on purpose that you're calling count on each iteration. PHP doesn't try to infer what you mean here, and neither should it. Therefore the standard way to do this is:
for ($i = 0, $length = count($myarray); $i < $length; $i++)
PHP will execute the count each time the loop iterates. However, PHP does keep internal track of the array's size, so count is a relatively cheap operation. It's not as if PHP is literally counting each element in the array. But it's still not free.
Using a very simple 10 million item array doing a simple variable increment, I get 2.5 seconds for the in-loop count version, and 0.9 seconds for the count-before-loop. A fairly large difference, but not 'massive'.
edit: the code:
$x = range(1, 10000000);
$z = 0;
$start = microtime(true);
for ($i = 0; $i < count($x); $i++) {
$z++;
}
$end = microtime(true); // $end - $start = 2.5047581195831
Switching to do
$count = count($x);
for ($i = 0; $i < $count; $i++) {
and otherwise everything else the same, the time is 0.96466398239136
PHP is an imperative language, and that means it is not supposed to optimize away anything that can possibly have any effect. Given that it's also an interpreted language, it couldn't be done safely even if someone really wanted.
Plus, if you simply want to iterate over the array, you really want to use foreach. In that case, not only the count, but the whole array will be copied (and you can modify the original one as you wish). Or you can modify it in place using foreach ($arr as &$el) { $el = ... }; unset($el);. What I mean to say is that PHP (as any other language) often provides better solutions to your original problem (if you have any).
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