Does while in this context have any cons over foreach?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ketrel
Forum Newbie
Posts: 6
Joined: Tue Sep 28, 2010 4:13 am

Does while in this context have any cons over foreach?

Post by Ketrel »

Does using 'while' in this manner have any cons compared to using foreach?

Code: Select all

while(list($key,$val) = each($array))
vs

Code: Select all

foreach($array as $key=>$val)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Does while in this context have any cons over foreach?

Post by Weirdan »

reset + while(list()=each()) is consistently slower than foreach() :

Code: Select all

weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) foreach($arr as $item) {$item=0;} '

real	0m0.483s
user	0m0.412s
sys	0m0.016s
weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) {reset($arr); while(list(,$item)=each($arr)) {$item=0;}} '

real	0m2.706s
user	0m2.636s
sys	0m0.004s
Ketrel
Forum Newbie
Posts: 6
Joined: Tue Sep 28, 2010 4:13 am

Re: Does while in this context have any cons over foreach?

Post by Ketrel »

Weirdan wrote:reset + while(list()=each()) is consistently slower than foreach() :

Code: Select all

weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) foreach($arr as $item) {$item=0;} '

real	0m0.483s
user	0m0.412s
sys	0m0.016s
weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) {reset($arr); while(list(,$item)=each($arr)) {$item=0;}} '

real	0m2.706s
user	0m2.636s
sys	0m0.004s
What if any additions were being appended, and reset wasn't used?
Post Reply