Is this foreach cycle responsible for killing cat gods?

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

Does the same code kill kittens too?

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

??

For those who have no idea what I'm talking about:

Is PHP getting longFile.txt every time it goes to the next line of the file or not? Speaking of this code:

 foreach (file("longFile.txt") as $line) { // something } 
+4
source share
5 answers

In a related question, the for loop takes a hit on performance by calling count on each iteration. foreach uses internal pointers to iterate over the array passed to it.

In your example, file() will be called once, and the resulting array will be passed to foreach , which will pass through it, so the kittens will be saved. Happy weather!

+5
source

You cannot kill all kittens, because in order for PHP to get the next line of the file, it must know the position of the file pointer from the previous line that was removed. You are only promoting an iterator that maintains a link to an object file.

In addition, it is bad practice to open such a file; you must have a variable to save it and close it when done.

+1
source

Is this file really big? Consider:

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

foreach always works on a specific iterator. If you pass array :

If the array is not specified, foreach works with a copy of the specified array, and not with the array itself. (ref)

Thus, no array or function call will be executed at every foreach step.

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

+1
source

You want to use a Duff device to loop around: http://de.wikipedia.org/wiki/Duff%E2%80%99s_Device . It will be faster than foreach and faster than a loop without using count () at each iteration, and it will be faster than concatenation and rtrim, but the same as using implode ().

+1
source

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

0
source

All Articles