Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate First Value in PHP Array when Imploding

$sql = "SELECT *
        FROM `likes`
        WHERE `pid` = $pid";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

$likers = array();

while($row = $result->fetch_assoc()) {
    $likers[] = $row['uid'];
    echo implode(", ", $likers);
}

} else {
    return "Be the first to like this status...";
}

For example, it should display the following if the query results in 3 rows with the user IDs: 21, 20, 44

It should display: 21, 20, 44 But instead, it displays: 2121, 20, 44 See how it displays the 1st value first?

Another example: 50, 60, 70 But it displays: 5050, 60, 70

Any way to fix? Thanks in advance

like image 765
Jordan Avatar asked Jun 15 '26 21:06

Jordan


1 Answers

You are printing the result inside the while loop, thats why it is happening. First there will be 21 in the array, then it will be 21, 20 and so on.Print it outside the loop.Try with -

while($row = $result->fetch_assoc()) {
    $likers[] = $row['uid'];    
}

echo implode(", ", $likers);
like image 197
Sougata Bose Avatar answered Jun 17 '26 22:06

Sougata Bose