jimbeeer Posted August 21, 2012 Share Posted August 21, 2012 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? 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. Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 21, 2012 Share Posted August 21, 2012 You'll need to return an array if you want more than one value. Quote Link to comment Share on other sites More sharing options...
jimbeeer Posted August 21, 2012 Author Share Posted August 21, 2012 but I'm just appending a variable out of the values of an array. As I said, echo works, but return doesn't. Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 21, 2012 Share Posted August 21, 2012 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. Quote Link to comment Share on other sites More sharing options...
trq Posted August 21, 2012 Share Posted August 21, 2012 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; } Quote Link to comment Share on other sites More sharing options...
jimbeeer Posted August 21, 2012 Author Share Posted August 21, 2012 Excellent. Thank you very much. It worked. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.