Link to home
Start Free TrialLog in
Avatar of Nathan Riley
Nathan RileyFlag for United States of America

asked on

PHP Loop Iteration Counts

What's a good method of determining the loop number you're on during a php while loop?

In my below code I need to delimit the variable($insightIDS) each loop with a comma, but if there is only 1 result or it's the last result of the loop I don't want to add a comma.

function getCustomRSSID($userID)
{
    include 'config.php';
    $sql="select insightID
              from usersInsights
              where userID = ".$userID;
    $result=$db->query($sql);
    $insightIDS = 0;
    while($row=$result->fetch_assoc()){

        $insightIDS .= $row['insightID'];

    }
    return $insightIDS;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of James Bilous
James Bilous
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There is also the rtrim() function to remove a collection of specific characters from the end of lines.
http://php.net/manual/en/function.rtrim.php
You might also write it like this.  (Different paths to the same end, 6+3=9, 7+2=9, etc)
function getCustomRSSID($userID)
{
    include 'config.php';
    $sql="select insightID
              from usersInsights
              where userID = ".$userID;
    $result=$db->query($sql);
    $insightIDS = [];
    while($row=$result->fetch_assoc()){

        $insightIDS[] = $row['insightID'];

    }
    return implode(',', $insightIDS);
}

Open in new window