Reputation: 6738
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.
Upvotes: 0
Views: 97
Reputation: 15374
In your first example, you're altering a copy of a string. $thisLine
is not a reference to the element in the array, but a copy of the array element.
In your second example, you are altering the array directly. You could use a foreach, but only if you go back to referencing the array:
foreach ($fileArray as $key => $thisLine) {
if ( condition ) {
$fileArray[$key] = "changed state";
}
}
Upvotes: 0
Reputation: 91734
$fileArray = file('blah.txt');
foreach ($fileArray as $key => $thisLine) {
if ( condition ) {
$fileArray[$key] = "changed state";
}
}
$newFileArray = implode('',$fileArray);
or passing by reference directly:
$fileArray = file('blah.txt');
foreach ($fileArray as &$thisLine) {
if ( condition ) {
$thisLine = "changed state";
}
}
$newFileArray = implode('',$fileArray);
Upvotes: 3