Posts Tagged ‘php’

How does return i++ work?

Sunday, December 13th, 2009

This came up while working on some code. I want to keep an internal counter within a function, and every time the function is called, return the incremented result. The function ended with return $i++; which, after I typed it, realized may not work as expected.

I wrote this quick test code to figure out what might happen.

<?php
function increment()
{
	static $count = 0;
	// do stuff
	return $count++;
}
 
for($i=0; $i<4; $i++)
{
	echo 'i=' . $i . ' return=' . increment() . "n";
}
?>

I figured one of three things might happen:

Option 1: $count is never incremented because return returns the pre-incremented value and prevents it from incrementing.

   i=0 return=0
   i=1 return=0
   i=2 return=0
   i=3 return=0

Option 2: $count is incremented and the incremented value is passed to return.

   i=0 return=1
   i=1 return=2
   i=2 return=3
   i=3 return=4

Option 3: The current value of $count is evaluated and passed to the return, $count is incremented, then the function returns.

   i=0 return=0
   i=1 return=1
   i=2 return=2
   i=3 return=3

Well it turns out that the function does what I wanted it to do, option 3. Can you explain why the value of $count can be incremented after the function returns?