Explode in a foreach

Is using explode() in a foreach a good idea? For example:

$var = "a\
foreach (explode("\
", $var) as $letter) {
    // ......

Will I experience performance issues, etc.?


As a general practice, what I would do is

$var = 'a/asdas/fgdfg/zfdvs/sdfh';
$array = explode('/', $var);
foreach ($array as $values)

Exploding outside the foreach statement makes it look cleaner.

Yes, I agree it is cleaner (that is how I typically do it), but what’s the actual effect on performance? How it is executed? Is this faster by not creating a variable or slower because in the loop construct? Or does this have no effect whatsoever at compile time? I’m not doing this for any speed gain, just curious.

Maybe this is better off in the Advanced PHP area.

edit: Basically I’d just like to know if this is ok to do; will I be using more resources if I execute code like this, although I most likely never will? It is silly to ask if I won’t be using it, but I’m curious to how this is compiled and executed. Anyone?

I’m pretty sure there is no difference in performance.

And no, this should go in the regular PHP forum. Advanced is for MVC and PHP theory discussion.

Actually, I believe that exploding outside of it is the way to go because doesn’t it execute the explode function over and over and just timeout?

It does work, although the explode()ed array is inaccessable because it is not set to a variable.

Does anyone have a more definite answer to this?

I would use $var = explode("
" $lines); then a foreach, this way you can actually access the variable, plus it’s not limited to only the foreach. I highly doubt 1 line will make any signifigant difference, it will have to do the same work either way.

I’m really looking for how this effects the memory/processor. What is this doing, if anything, differently at the bits and bytes level? Wrong place to ask?

I understand the PHP part fully (coding 4+ years), but I have little experience “under the hood” with PHP.

I don’t even think you could really measure this, unless you had a dedicated server. As I said, it would not be a considerable difference, nanoseconds I’d say, and I’m not even sure which way is higher or lower. If you happen to have a dedicated server I’d run a test and get the load time, run multiple times and average it out, each time.