Thread: Function loop

    #1
  1. User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Location
    UK
    Posts
    471
    Rep Power
    76

    Question Function loop


    Hey all,
    I'm in a serious dilemma. I am developing a wordpress theme and I'm just working on the comments section, this is all fine until I start dealing with nested comments, I have a function which takes a posts id and does all the necessary scripting to return a list of all the comments. I won't post my code as it is very long but instead post a description of it:
    Code:
    function comments($id){
    $echo='';
    $comments =  get_comments($id);
    $noComments = count($comments);
    if($noComments != 0){
    foreach($comments as $comment):
    $echo .= '<h1>.$user.'</h1>';
    $echo .= '<p>'.$post.'</p>';
    //Here I want to display the nested comments
    endforeach;
    }
    echo $echo;
    }
    I know that's really brief but rather than pasting code for nested comments (which is identical) several times, Could I call the same function from within itself?? It's a really weird concept, but there must be some way of looping a function, it wouldn't go on forever because eventually the nested comments would stop, the count would be at 0 then the php could continue the next for loop...?? It's perfectly simple if I just paste the code 10 times and hope users never post comments more than 10 levels in.
    I hope you have a vague idea of what I am getting at here, this isn't a wordpress or php specific question as I have the coding knowledge, but any ideas as to how to approach this would be really useful because I can't think of a way of doing this.
    Cheers,
    Sephers.
  2. #2
  3. Wiser? Not exactly.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    5,946
    Rep Power
    4037
    Originally Posted by sephers181
    Could I call the same function from within itself?? It's a really weird concept, but there must be some way of looping a function,
    It's called recursion.

    Comments on this post

    • sephers181 agrees : I O U a beer xD
    Recycle your old CD's, don't just trash them



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  4. #3
  5. User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Location
    UK
    Posts
    471
    Rep Power
    76
    that's brilliant, thanks so much. I've been coding for years and I've never heard/done any of this but its going to be really interesting to learn about. Cheers.

IMN logo majestic logo threadwatch logo seochat tools logo