Search code examples
phpmysqlarraysimplode

Implode a single column of values from a query result set


I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...

$sql = mysql_query("SELECT follows
            FROM follow 
             WHERE follower LIKE '".$id."'") or die (mysql_error());

if (mysql_num_rows($sql) < 1) {
    echo "<br/>";
    echo "Follow someone";
} else {
    //Put all the id's of the users the user is following in an array. 
    $i = 0;
    $user_follows = array();
    while ( $row = mysql_fetch_assoc($sql) ) {
        $user_follows[$i] = $row;
        $i++;
    }

    $user_follows = implode(" , ", $user_follows);
    echo $user_follows;
}

Solution

  • The second argument to implode must be an array of strings. But you're doing:

    $user_follows[$i] = $row;
    

    Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:

    $user_follows[] = $row['follows'];
    

    You don't need the $i variable, assigning to $array[] appends a new element to the array.