Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange behavior while modifying array that is being iterated
    primarykey
    data
    text
    <p>This is a stupid example, but shows exactly what is my problem. In some situations the array is sucessufully modified and anothers it is not, why? Values are given to foreach by value? And the output is also screwed, some lines seems to have '\r\n' others do not. <pre><code>$arr = file('text.txt'); echo '&lt;pre&gt;'; foreach( $arr as $x =&gt; $line){ if( $x % 3){ unset( $arr[$x]); } // this works else{ $arr[$x+1] += 1;} // this don't echo "[$x] =&gt; ${arr[$x+1]}"; } print_r( $arr); </code></pre> <p>text.txt:</p> <blockquote> <p>0<br/> 1<br/> 2<br/> 3<br/> 4<br/> 5<br/> 6<br/></p> </blockquote> <p>output:</p> <blockquote> <p>[0] => 2[1] => 2<br/> [2] => 3<br/> [3] => 5[4] => 5<br/> [5] => 6[6] => 1Array<br/> (<br/> &nbsp;&nbsp;&nbsp;&nbsp;[0] => 0<br/> <br/> &nbsp;&nbsp;&nbsp;&nbsp;[3] => 3<br/> <br/> &nbsp;&nbsp;&nbsp;&nbsp;[6] => 6<br/> &nbsp;&nbsp;&nbsp;&nbsp;[7] => 1<br/> )</p> </blockquote> <p><strong>EDIT:</strong></p> <p>The example didn't really accomplish anything, it was useless just to show that something unexpected happened, so, here is something closer to what I need to do:</p> <pre><code>&lt;?php $arr = file('text.txt'); echo '&lt;pre&gt;'; foreach( $arr as $x =&gt; $line){ if( preg_match("/word$/", $line)){ $line = preg_replace( "/word$/", '', $line); $arr[$x+1] = 'word ' . $arr[$x+1]; } } print_r( $arr); </code></pre> <p>text.txt:</p> <blockquote> <p>test0<br/> test1word<br/> test2<br/></p> </blockquote> <p>expected values in the array:</p> <blockquote> <p>[0] => test0<br/> [1] => test1<br/> [2] => word test2<br/></p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload