Jump to content

Which is more efficient?


aximbigfan

Recommended Posts

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

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

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

@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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.