简体   繁体   中英

Have days display with commas except for the last one

I have the following if statements that gather up all the days that were selected before it becomes displayed.

$daysUsed = "";

if($this->dayweeksunsession==1){
    $daysUsed .= "Su ";
}

if($this->dayweekmonsession==1){
    $daysUsed .=  "M ";
}

if($this->dayweektuessession==1){
    $daysUsed .=  "T ";
}

if($this->dayweekwedsession==1){
    $daysUsed .=  "W ";
}

if($this->dayweekthurssession==1){
    $daysUsed .=  "Th ";
}

if($this->dayweekfrisession==1){
    $daysUsed .=  "F ";
}

if($this->dayweeksatsession==1){
    $daysUsed .=  "Sa ";
}

if($daysUsed !=="") {
    echo "</span><br/>Days of the Week: <span class='BoxReviewOutput'>";
    echo $daysUsed;
}

My question here is how can I make this so that commas will be displayed for each day of the week that was chosen in the session except for the last one.

For example: Sunday and Tuesday were chosen. So it would be displayed "Su, T"

Thanks in advance!

Use implode()

$days = array("Su", "M", ....., "Sa");
echo implode(",", $days);

In your ifs add a commma:

$daysUsed = "Whatever, ";

Then before you output the final string:

$daysUsed = substr($daysUsed, 0, -2);

EDIT: -1 needs to be -2, to account for the spacing between days.

i'd use an array and implode it but in your case i'd need to use this

echo substr($daysUsed,0,-1)

in this case I remove the last character from the string

$daysUsed = trim( $daysUsed, "," );

trim() is by far the better option - minimal function, does what you want for your intended purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM