Jump to content

Need help returning a value from a foreach loop


eldan88

Recommended Posts

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