0

I am trying to create a php string with integers separated by commas. The values for the string are coming from a do { }while loop. How would I do this?

//GRAB EC DATA
    $mysql_ec_data = "SELECT `ec_c_id` FROM `e_c` WHERE `ec_id` = '$e_id'";
    $query_ec_data = mysql_query($mysql_ec_data) or die(mysql_error());
    $ec_data = mysql_fetch_assoc($query_ec_data);   

    $string = "";           
    do {

        //There will be values looping through here that I want to add to a single string.
        $string =+ $ec_data['ec_id'];               

    } while ($ec_data = mysql_fetch_assoc($query_ec_data)); 
    //this is how the values from the while loop should look in the string at the end
    $string = 45,52,23;
1
  • 1
    $string .= $ec_data['ec_id'] . ","; ?? this? Commented Feb 23, 2014 at 18:57

3 Answers 3

2

Use this:

$string .= $ec_data['ec_id'] . ', '; 
Sign up to request clarification or add additional context in comments.

Comments

2

You could use $string =+ $ec_data['ec_id'] . ", "; and after the loop remove the last comma with PHP substr method: https://www.php.net/substr

$string = substr($string, 0, -1);

Comments

2

Be careful with your assignment-concatenation operator, in PHP it is .=. A simple way to handle the comma delimiter is to first put the integers in an array and then "glue" them together after the loop:

$string = "";
$integers = array();           
do {
    $intgers[] = $ec_data['ec_id'];               

} while ($ec_data = mysql_fetch_assoc($query_ec_data)); 

if (count($integers)) {
   $string = implode(",", $integers);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.