开发者

is there a reason to use ++$i in for loop?

开发者 https://www.devze.com 2023-01-25 07:12 出处:网络
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 mat

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

0

精彩评论

暂无评论...
验证码 换一张
取 消