mfv 0 Newbie Poster

Hello, I can't give an array a value from within a recursive function,
I'm trying to iterate a multi dimensional array and get the items that match the if statement.

I tried both techniques suggested above but none of them worked, here is my code:

$path = array();

function getpath($arreg, $lft = null, $rgt = null){

	foreach ($arreg as $key => $val){

		if (is_array($val)) {			
		
			if($key === 'Node') {
				
				if( $val['lft'] <= $lft && $val['rght'] >= $rgt ) {	
				global $path;
					$path[] = $val['id'];						
				}

			}
			
			getpath($val, $lft, $rgt);	
	
		}
		
	}	
	
}

getpath($nodes, $pageinfo['Node']['lft'], $pageinfo['Node']['rght']);

if I print_r($path), after calling the function, it is still empty, any help is appreciated.

Hey.

To add to an array from withing a recursive function, you need to either import a global variable into the function, or pass it as a reference parameter.

$myArray = array();
function setValue($value) {
  if($value < 100) {
    global $myArray;
    $myArray[] = $value;
    setValue($value+1);
  }
}
function setValue($value, &$myArray) {
  if($value < 100) {
    $myArray[] = $value;
    setValue($value+1);
  }
}

$myArray = array();
setValue(1, $myArray);

I would recommend the second option, because it gives you more control over how the variables are handled.

If this is not what you are talking about, please explain this better. Code examples are also very helpful.