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
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.

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.