P. Nick P. Nick - 4 months ago 11
PHP Question

PHP implode A, B, C and X others

Currently I have some code that retrieve names and lists them like

User1, User2 and User3 likes this


$MoreLikers = $this->DBHandle->mysqli->query("SELECT * FROM thread_reply_likes WHERE post_receiver = '".$Row["id"]."'");
while($FetchLikers = $MoreLikers->fetch_array()) {
$like_user = $this->DBHandle->mysqli->query("SELECT * FROM users WHERE id = '".$FetchLikers["user_giver"]."'");
$LuArray = array();
while($RowLu = $like_user->fetch_array()) {
$LuArray[] = $RowLu;
}

$LuArrayz[] = "";

foreach($LuArray as $Rowz) {
$TheLikersList[] = $Rowz["username"];

}

if($MoreLikers->num_rows < 4) {
$last = array_slice($TheLikersList, -1);
$first = join(', ', array_slice($TheLikersList, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
$TheLikers = join(' and ', $both);

$ListLikers = "<i class='fa fa-thumbs-up'></i> " . $TheLikers . " likes this";
} else {
// what to put here if num_rows are more than 3?
}
}


What I want to do is, if the numbers of users (num_rows basically) are more than 3, to show it like
User1, User2, User3 and X others likes this
where X is the
num_rows
minus
3
.

I'm not sure how to do that. Any help is appreciated!

Answer

Insert $MoreLikers->num_rows in the middle :

if($MoreLikers->num_rows < 4) {
        $last  = array_slice($TheLikersList, -1);
        $first = join(', ', array_slice($TheLikersList, 0, -1));
        $both  = array_filter(array_merge(array($first), $last), 'strlen');
        $TheLikers = join(' and ', $both);
        $ListLikers = "<i class='fa fa-thumbs-up'></i> " . $TheLikers .
                      " likes this";
} else {
    $three  = array_slice($TheLikersList,0,3);
    $TheLikers = join(', ', $three);
    $ListLikers = "<i class='fa fa-thumbs-up'></i> " . $TheLikers .
                  " and " . ($MoreLikers->num_rows-3) . " others like this"; //<=======
    }