0

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?

2
  • 3
    ya know .. some people actually read documentation, before they start reporting "bugs". Commented Feb 13, 2012 at 20:56
  • I read It, but that is easily overlooked. Such importat thing should be more clearly emphasized. Guess I sould have written "bug" :) Commented Feb 13, 2012 at 21:00

2 Answers 2

8

$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.

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me by a minute. A well earned +1.
This explains it well. Thanks.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.