user1479891
user1479891

Reputation: 149

PHP transform array in comma seperated string

I can't seemn to make this work could someone help identify what is incorrect:

$result = mysql_query("SELECT accounts_client_email.client_email FROM accounts_client_email WHERE accounts_client_email.accounts_client_id = 1", $con);

while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row; // Inside while loop
}

$tags = implode(', ', array($new_array));

echo $tags;

Upvotes: 0

Views: 158

Answers (5)

MythThrazz
MythThrazz

Reputation: 1647

If you just need a comma separated string, not an array, you can do it like this:

while( $row = mysql_fetch_assoc( $result))
{
    if(empty($tags)
        $tags = $row['client_email'];
    else
        $tags .= ', '.$row['client_email'];
}
echo $tags; //will display comma separated string - no arrays needed

Upvotes: 0

user1578358
user1578358

Reputation: 26

use for loop

$array_to_string="";
for($i=0;$i<=count($result_array)-1;$i++)
{
    if($i != count($result_array)-1)
    {
        $array_to_string .= $result_array[$i].",";
    }else
    {
        $array_to_string .= $result_array[$i];
    }
}
echo $array_to_string; // you get the string as a commoa seperated values which is available in the array

Upvotes: 0

Correia JPV
Correia JPV

Reputation: 610

You need to use brackets

$new_array[] = $row[]; // Inside while loop

If this doesnt work, use

 $new_array[] = $row['client_email']; // Inside while loop

Upvotes: 1

Fabio
Fabio

Reputation: 23480

I think you just need to use scope with your column name to populate in your array

while( $row = mysql_fetch_assoc( $result))
{
    $new_array[] = $row['client_email']; // Inside while loop
}

I would like to also to remember you that mysql_* functions are officially deprecated and no longer maintained so i would advise you to switch to mysqli or PDO for new projects.

Upvotes: 1

aleation
aleation

Reputation: 4844

You aren't adding correctly to the array, it should be:

$new_array[] = $row['client_email'];

And you are encapsulating the array into another array unnecessarily;

use:

$tags = implode(', ', $new_array);

Or echo $tags; will just output "Array"

Upvotes: 1

Related Questions