Page 1 of 1

incrementing recursive reference fails [SOLUTION: RTFM!]

Posted: Tue Mar 06, 2007 7:30 am
by Popcorn
Bit nervous about this but here goes ....
What do you think this prints?

Code: Select all

$tree = array ('val' => '-root-', 'children' => array (
	1 => array ('val' => 'one', 'children' => array (
		2 => array ('val' => 'two', 'children' => array ()))),
	3 => array ('val' => 'three', 'children' => array (
		4 => array ('val' => 'four', 'children' => array ())))));
function prarray ($tree, &$index=null) {
	print "\n  ".$index.' '.$tree['val'];
	foreach($tree['children'] as $subtree)
		prarray($subtree, ++$index);
}
prarray($tree,$i=0);
Because I get $index nicely incrementing in PHP version 5.1.0 and not in 5.2.0.
Any changes I should know about (couldn't spot any in the changelogs) or more likely, any idiocy on my part?
(Installing 5.2.1 now to have a look)

Posted: Tue Mar 06, 2007 7:41 am
by volka
Not sure what the expected result is but try

Code: Select all

foreach($tree['children'] as $subtree) {
  $index += 1;
  prarray($subtree, $index);
}

Posted: Tue Mar 06, 2007 8:02 am
by Popcorn
yup, that is also my fix.
The issue is the same with 5.2.1

expected result:
0 -root- 1 one 2 two 3 three 4 four
actual result:
0 -root- 1 one 2 two 2 three 3 four

In the initial call using:

Code: Select all

$i=0;
prarray($tree,$i);
and leaving the fn alone also works.

Is it just me or do there seem to be several times when the references seem to behave funnily? :S

Posted: Tue Mar 06, 2007 9:19 am
by Popcorn
OK, so the docs say it: http://www.php.net/manual/en/language.r ... s.pass.php

Code: Select all

foo($a = 5); // Expression, not variable
I now have to go and say "RTFM!" to myself
... that hurt.

and the expression thing:
http://www.php.net/manual/en/language.expressions.php
in the paragraph beginning: "PHP takes expressions much further.."

I think lots of my code passes expressions ... *sinking feeling*

Posted: Tue Mar 06, 2007 9:24 am
by feyd
In the end it's better (more readable for others) to not write complex statements such as those posted so far.