Jump to content

Passing variables out of a function


jimbeeer

Recommended Posts

I'm trying to pass a variable that's been built with a foreach loop inside a function.

 

With 'echo' it creates it properly.

 

With 'return' it only passes the last part.

 

What on earth am I doing wrong?  :confused:

 

function busLocation($nodesLoc, $all, $spacing=''){ 
    $returnQuery = "";
    foreach($nodesLoc as $n){ 
          $returnQuery .= " {$n['bus_location_id']}"; 
          if(isset($all[$n['bus_location_id']])){ 
            busLocation($all[$n['bus_location_id']], $all, $spacing); 
          } 
    } 
	echo $returnQuery;
}

 

displays: 16 17 13 12 14 11

 

But if I do:

 

function busLocation($nodesLoc, $all, $spacing=''){ 
    $returnQuery = "";
    foreach($nodesLoc as $n){ 
          $returnQuery .= " {$n['bus_location_id']}"; 
          if(isset($all[$n['bus_location_id']])){ 
            busLocation($all[$n['bus_location_id']], $all, $spacing); 
          } 
    } 
	return $returnQuery;
}

 

and then do:

 

echo busLocation($nodesLoc[0], $nodesLoc);

 

it displays: 11

 

Which is the last number in the foreach loop.

 

Does anyone have any ideas what I'm doing wrong?

 

I'm aware that return exits the function but I didn't think the echo/return would be building up the loop, just the foreach, and then the final line within the function would only be called once.

Link to comment
https://forums.phpfreaks.com/topic/267373-passing-variables-out-of-a-function/
Share on other sites

Wait, this is a recursive function, but you're not doing anything with the value it returns when you call it within itself. In the "middle" you have busLocation($all[$n['bus_location_id']], $all, $spacing);

And you don't capture the value returned by it.

What you have there is a recursive function. Your not saving the returned value of the inner function call.

 

function busLocation($nodesLoc, $all, $spacing=''){ 
    $returnQuery = "";
    foreach($nodesLoc as $n){ 
        $returnQuery .= " {$n['bus_location_id']}"; 
        if (isset($all[$n['bus_location_id']])) { 
            $returnQuery .= busLocation($all[$n['bus_location_id']], $all, $spacing); 
        } 
    } 
    return $returnQuery;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.