eldan88 Posted July 6, 2014 Share Posted July 6, 2014 (edited) Hey Guys. I have a custom function that simply loops through an array and outputs the menu categories it finds in the array. The foreach loop passes the function an array and the function returns the the value. The problem is that the function returns that last value. Now I know some of you might say ... "Why don't you put the foreach inside the function and return the value when the foreach loop has been completed" The reason why is because I to use that foreach loop through another function as well. I was thinking about using globals to get the return value. But just wanted to get your perspective on the best option here. Please let me know what you guys think Thanks User Defined Function function displayMenuCategories($menu_category){ $display_menu =""; $category_id = $menu_category['menu_cat_id']; $display_menu .= "<div class='menu_cat'>{$menu_category['menu_cat_name']}</div><br>\n"; if(!empty($menu_category['menu_cat_desc'])) { $display_menu .= "<div class='menu_desc'>{$menu_category['menu_cat_desc']}</div>\n"; } $category_info = array("display" => $display_menu, "category_id" => $category_id ); return $category_info; } Foreach loop $left_menu_categories // Is the array that contains all the menu categories foreach($left_menu_categories as $left_menu_category){ $get_categories = displayMenuCategories($left_menu_category); } var_dump($get_categories); Edited July 6, 2014 by eldan88 Quote Link to comment https://forums.phpfreaks.com/topic/289496-need-help-returning-a-value-from-a-foreach-loop/ Share on other sites More sharing options...
trq Posted July 6, 2014 Share Posted July 6, 2014 So, if you want multiple categories, $get_categories needs to be an array. Quote Link to comment https://forums.phpfreaks.com/topic/289496-need-help-returning-a-value-from-a-foreach-loop/#findComment-1484051 Share on other sites More sharing options...
eldan88 Posted July 6, 2014 Author Share Posted July 6, 2014 And then I would have to run another foreach loop on $get_categories? Quote Link to comment https://forums.phpfreaks.com/topic/289496-need-help-returning-a-value-from-a-foreach-loop/#findComment-1484055 Share on other sites More sharing options...
trq Posted July 7, 2014 Share Posted July 7, 2014 Most likely. Quote Link to comment https://forums.phpfreaks.com/topic/289496-need-help-returning-a-value-from-a-foreach-loop/#findComment-1484057 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.