Is it necessary to store the result of explode()
if all it will be used for is a loop?
$lines = explode(PHP_EOL, $data);
foreach ($lines as $line) {
// do stuff
}
Is there any reason not to call it directly within the loop? Will explode()
be called once, or for every iteration?
foreach (explode(PHP_EOL, $data) as $line) {
// do stuff
}
explode()
will only be called once inside your foreach
loop, if you have a very big code, you will have two choices:
Each variable holds some bytes of the memory, so if you have a big web application, i suggest calling the explode()
inside the foreach
, but if your application isn't that big, i don't think it will hurt to allocate some bytes.
The second option, is a clean code, if you assign your explode
to a variable, it will be useful for later uses, and it will also make it easier to debug.
I'd like also to recommend this article for more informations.