Hyperion
Hyperion

Reputation: 909

PHP removing last 2 characters from a while loop string

I am returning a list in a loop statement and trying to remove the last two chars from the result: a comma and space.

Here is my class function for it before I tried to use trim, rtrim, implode and strlength

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo $nameRow['username']."(".$pullrow['char_name']."), ";
        }
    }
}

How can I remove the final separator?

Upvotes: 0

Views: 582

Answers (3)

Mubo
Mubo

Reputation: 1070

I think you can also use the substr function such as the following:-

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo substr($nameRow['username']."(".$pullrow['char_name']."), ", 0, -2);
        }
    }
}

Upvotes: 0

cOle2
cOle2

Reputation: 4784

Instead of messing with rtrim, substr or similar it may be easier for you to keep an array of results and them implode them. This way you will not have to keep track of which is the last record or how many characters you will need to strip:

function ReturnPlayerList()
{
    global $sql;
    $result = array();
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            $result[] = $nameRow['username']."(".$pullrow['char_name'].")";
        }
    }
    echo implode(", ", $result);
}

Upvotes: 5

Joel Jaime
Joel Jaime

Reputation: 469

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo rtrim($nameRow['username']."(".$pullrow['char_name']."), ",", ");
        }
    }
}

Upvotes: 0

Related Questions