3
votes

As taken from https://stackguides.com/questions/4891301/top-bad-practices-in-php

Is this similar code killing kittens, too?

foreach (file("longFile.txt") as $line) {
    // ouch! Kitten killed
}

??

For those who have no idea what am I talking about:

Is PHP getting longFile.txt everytime it goes to next line of file or no? Talking about this code:

foreach (file("longFile.txt") as $line) {
        // something
}
5
Going to the next line of file actually would be better than loading it into memory completely, right? See my answer how to do that with PHP.hakre

5 Answers

5
votes

In the linked question the for loop incurs a performance hit by calling count on every iteration. foreach uses internal pointers to iterate through the array passed to it.

In your example file() will be called once and the resulting array will be passed to foreach which will iterate through it, thus the kittens are saved. Happy Caturday!

1
votes

It shouldn't be killing any kittens, since, in order for PHP to get the following line of the file, it has to know the position of the file pointer since the previous line that was pulled off. You are only advancing the iterator, which maintains a reference to the file object.

Also, it's bad practice to be opening a file like that; you should have a variable to store it in and close it when you're done.

1
votes

You want to use a Duff Device to unroll the loop: http://de.wikipedia.org/wiki/Duff%E2%80%99s_Device. This would be faster then foreach and faster then for loop without using count() on each iteration and it would be faster then concatenating and rtrim the string but the same like using implode().

1
votes

Is that file really large? Consider:

foreach(new SplFileObject($path) as $line) {
    // neither kill puppies nor kittens
}

foreach works always on the concrete iterator. If you're passing an array:

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. (ref)

So nor array or function call will executed each time the foreach steps ahead.

Related: How to store and reset a PHP array pointer?

0
votes

No. There are many reasons why kittens die, but foreach loops are not one of them.