I had an array which contained lines of a file that I had to process, each element of the array was a line of the file. After processing I implode the file, write it out and use it.
When I tried to use foreach for this, it didn’t work. I had a suspicion that it was creating a copy of the element rather than referencing the element directly, so used a for loop instead, which did work.
My question is, is there some way to use a foreach loop in this scenario or when redefining elements of an array must you always use a for loop?
Example code:
$fileArray = file('blah.txt');
foreach ($fileArray as $thisLine) {
if ( condition ) {
$thisLine = "changed state";
}
}
$newFileArray = implode('',$fileArray);
Didn’t work vs:
$fileArray = file('blah.txt');
for ($x=0;$x<count($fileArray);$x++) {
if ( condition ) {
$fileArray[$x] = "changed state";
}
}
$newFileArray = implode('',$fileArray);
Which worked fine.
or passing by reference directly: