incrementing recursive reference fails [SOLUTION: RTFM!]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Popcorn
Forum Commoner
Posts: 55
Joined: Fri Feb 21, 2003 5:19 am

incrementing recursive reference fails [SOLUTION: RTFM!]

Post 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)
Last edited by Popcorn on Tue Mar 06, 2007 9:30 am, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Not sure what the expected result is but try

Code: Select all

foreach($tree['children'] as $subtree) {
  $index += 1;
  prarray($subtree, $index);
}
User avatar
Popcorn
Forum Commoner
Posts: 55
Joined: Fri Feb 21, 2003 5:19 am

Post 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
User avatar
Popcorn
Forum Commoner
Posts: 55
Joined: Fri Feb 21, 2003 5:19 am

Post 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*
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

In the end it's better (more readable for others) to not write complex statements such as those posted so far.
Post Reply