Echo a comma on all but the last value? (result from mysql_fetch_array)

后端 未结 11 1948
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 22:56

How do I echo a comma on all but the last value? Here\'s my code:

while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {

    ECHO $servdescarrayrow         


        
相关标签:
11条回答
  • 2020-12-21 23:37
    $array = array();
    while ($servdescarrayrow = mysql_fetch_array($servdescarray))
        $array[] = $servdescarrayrow['serv_desc'];
    ECHO implode(',', $array);
    
    0 讨论(0)
  • 2020-12-21 23:38

    Here's one possible way. Not very graceful, but does the job:

    $Ix = 0;
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        if ($Ix > 0)
            echo ",";
        $Ix++;
        echo $servdescarrayrow['serv_desc'];
    }
    
    0 讨论(0)
  • 2020-12-21 23:39

    Why not:

    if ($servdescarryrow = mysql_fetch_array($servdescarray)) {
        echo $servdescarryrow;
    }
    
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        ECHO ",".$servdescarrayrow['serv_desc'];
    }
    
    0 讨论(0)
  • 2020-12-21 23:44

    you can remove the last comma after generating the string like so:

    $str = '';
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
       $str .= $servdescarrayrow['serv_desc'].",";
    }
    $str = substr($str, 0, strlen($str) - 1);
    echo $str;
    
    0 讨论(0)
  • 2020-12-21 23:46

    I am wondering why there was a dozen answers to your first question and noone to answer the edited part.

    Nope, it shouldn't work. Because $servdescarrayrow variable represents only one row and you and thus the whole code makes no sense.

    Although you can involve the number of returned records into process and get desired result, I doubt you really need that.

    Not to mention that with the way you echo, you will always have the trailing comma anyway.

    0 讨论(0)
提交回复
热议问题