April 11, 2012

Have days display with commas except for the last one

Question by Nina

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!

Answer by Josh

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.

Answer by Starx

Use implode()

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!