Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.