Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Displaying consecutive days with non-consecutive days.

1. ## Displaying consecutive days with non-consecutive days.

Ok, I think I'm having a Monday morning brain fart here. I know there's a simple solution that I'm missing. Here's the situation...

I'm reading days open for a store location in the database and placing that data into an array that ends up like this...

Code:
```\$days_open = array(
'Mon','Thurs','Fri','Sat'
);```
and
Code:
```\$days_closed = array(
'Sun','Tue','Wed','Thurs'
);```
I want to display...

Open: Mon, Thurs-Sat
Closed: Sun, Tue-Thurs

I've tried a few different approaches, but nothing seems to work for all the various combinations.

Any ideas?

PS: Assuming Sunday is the start day of the week

• You could assign keys to the arrays, representing the day of the week, and as you foreach, check if the last key and the current key are consecutive, and if the current key is the last key. If it is consecutive and not the last, skip it, and if it is the last, put it in.

• Here's a hackish way of doing it:
PHP Code:
``` function days_concat( Array \$days ){    // Define all days of the week    static \$all_days = array(        'Sun', 'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat'    );    // prepare our output    \$output = array();    // loop through all days of the week    foreach ( \$all_days as \$i => \$day )    {        // if it is included, grab it        if ( in_array( \$day, \$days ) )        {            \$output[] = \$day;        }        // ...otherwise, mark it with a hash        else        {            \$output[] = '#';        }    }    // clean everything up    \$output = implode( '#', \$output );    \$output = trim( \$output, '#' );    // two or more consecutive hashes = days that are two or more apart    \$output = preg_split( '/##+/', \$output, NULL, PREG_SPLIT_NO_EMPTY );    // turn consecutive days into dashed days    foreach ( \$output as \$i => \$value )    {        \$output[ \$i ] = preg_replace( '/#(\w+#)*/', '-', \$value );    }    // format with commas    \$output = implode( ', ', \$output );    // send it on it's way!    return \$output;}  ```
Usage:
PHP Code:
``` // Mon, Thursecho days_concat( array( 'Mon', 'Thurs' ) );// Mon, Wed-Thursecho days_concat( array( 'Mon', 'Wed', 'Thurs' ) );// Mon, Wed-Friecho days_concat( array( 'Mon', 'Wed', 'Thurs', 'Fri' ) );// Sun-Tue, Thurs-Satecho days_concat( array( 'Sun', 'Mon', 'Tue', 'Thurs', 'Fri', 'Sat' ) );  ```
...eh, get's the job done.

• Thanks. Seems to do the trick.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•