Reputation: 48755
I think I stumbled across a bug in PHP. However, to be sure, I am asking here first.
$k=0;
echo preg_replace_callback('/./', function($groups) use ($k) {
return $k++;
}, 'xxxxxx');
Script output: 000000
Expected output: 012345
Am I missing something?
Upvotes: 0
Views: 94
Reputation: 174987
The anonymous function is called every time a match is found, the state of $k is not preserved during (hence, the closure).
Try passing it by reference, or use a global.
Upvotes: 2
Reputation: 101936
$k
is bound to the closure by value, not by reference. So it will always be the same between multiple closure calls.
You can also pass it by reference using &$k
. Note that this will also modify the $k
value outside the closure.
Upvotes: 8