6

NikiC stated in another thread:

Right before [a foreach] iteration the $array is "soft copied" for use in foreach. This means that no actual copy is done, but only the refcount of the zval of $array is increased to 2.

However, my test code is showing a different result:

$array = array(0, 1, 2); xdebug_debug_zval('array'); // refcount=1, is_ref=0 // so far so good foreach ($array as $key => $value) { xdebug_debug_zval('array'); // refcount=3, is_ref=0 } // why is refcount 3 instead of 2? 

Just by looking at the code, we can see at most two array variables.

Why is refcount 3?

Why isn't refcount 2 after foreach is run?

8
  • In your foreach loop shouldn't you refer to your array element using the $value variable? Commented Aug 10, 2013 at 4:03
  • @Crackertastic, I'm not using any variables within the loop. Commented Aug 10, 2013 at 4:04
  • 1
    I'm getting refcount 2, am I missing something? array: (refcount=2, is_ref=0)=array (0 => (refcount=1, is_ref=0)=0, 1 => (refcount=1, is_ref=0)=1, 2 => (refcount=2, is_ref=0)=2) Commented Aug 10, 2013 at 4:07
  • @vinodadhikary, you ran the exact same code without modification? I'm on 5.3.26, what about you? Commented Aug 10, 2013 at 4:08
  • PHP 5.5.1, I get refcount=2. Commented Aug 10, 2013 at 4:09

1 Answer 1

1

The xdebug_debug_zval() is looking at the $array variable and not the $key variable. if you change your code to:

foreach ($array as $key => $value) { echo $key . " : " . $values . "<br>"; //xdebug_debug_zval('array'); } 

The correct values of the array will be returned. I don't have the xdebug function so I can't test what value you put in there.

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

6 Comments

I've tested your code and xdebug_debug_zval('array'); still shows 3 instead of 2. I'm not testing the values of the array, but the refcount of the array.
OK. While in the foreach loop you will need to change the xdebug... value. At the moment you are always looking at the entire array not the item in the array.
I don't want to look at the item in the array.... I'm looking at the array because that is what this question is about. Why does the array give refcount 3 instead of 2?
As I have said I don't have the xdebug thingy. I would report it as a bug to the creators of the plugin.
Thank you for the info but I don't need it as I use phpED as my IDE. I would still report this bug.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.