aximbigfan Posted January 10, 2009 Share Posted January 10, 2009 Which one of these method is the better way? (IE, more efficient) // Method one $str = '1|2|3|4|5|6'; foreach (explode('|', $str) as $key=>$val) { //Do something here } // Method 2 $str = '1|2|3|4|5|6'; $arr = explode('|', $str); foreach ($arr as $key=>$val) { //Do something here } Normally, I just use method 1. Will PHP run that function every alliteration, or will it run it once, and cache the array? I would think it would just cache the array... Thanks, Chris Link to comment https://forums.phpfreaks.com/topic/140325-which-is-more-efficient/ Share on other sites More sharing options...
Prismatic Posted January 10, 2009 Share Posted January 10, 2009 Which one of these method is the better way? (IE, more efficient) // Method one $str = '1|2|3|4|5|6'; foreach (explode('|', $str) as $key=>$val) { //Do something here } // Method 2 $str = '1|2|3|4|5|6'; $arr = explode('|', $str); foreach ($arr as $key=>$val) { //Do something here } Normally, I just use method 1. Will PHP run that function every alliteration, or will it run it once, and cache the array? I would think it would just cache the array... Thanks, Chris Method 2. In method 1 you're calling explode each iteration Link to comment https://forums.phpfreaks.com/topic/140325-which-is-more-efficient/#findComment-734279 Share on other sites More sharing options...
corbin Posted January 10, 2009 Share Posted January 10, 2009 I'm not sure about older versions of PHP, but I think it would cache it in the newer versions. (If it didn't cache it, it would be an infinite loop ;p.) C:\Users\Corbin>php -r "function a() { echo 'a executed'; return array(1,2,3); } foreach(a() as $v) echo $v;" a executed123 Link to comment https://forums.phpfreaks.com/topic/140325-which-is-more-efficient/#findComment-734283 Share on other sites More sharing options...
aximbigfan Posted January 10, 2009 Author Share Posted January 10, 2009 @Corbin, I would have to agree, at least from a logical standpoint. Anyone wanna give this a shot on an older version of PHP (blatent rip off of Corbin's) function RetArr() { echo "Function Run"; return array (1, 2, 3); } foreach (RetArr() as $val) { echo $val; } On PHP 5.2.4 I get "Function Run123" which is expected. Chris Link to comment https://forums.phpfreaks.com/topic/140325-which-is-more-efficient/#findComment-734302 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.