php include file based on day of the week - concise code?

52 views Asked by At

I've used answers to some of the previous questions on stack overflow (thanks everyone) to come up with an associative array that includes a particular file based on the day of the week but I was wondering if there is a way of making the code more concise as the path names seem long and repetitive?

$today = date("l");

$content = array (

"Sunday" => "/home/josull05/htdocs/wdd4/php/main-content/sundays-activities-home.php", "Monday" => "/home/josull05/htdocs/wdd4/php/main-content/mondays-activities-home.php", "Tuesday" => "/home/josull05/htdocs/wdd4/php/main-content/thursdays-activities-home.php", "Wednesday" => "/home/josull05/htdocs/wdd4/php/main-content/wednesdays-activities-home.php", "Thursday" => "/home/josull05/htdocs/wdd4/php/main-content/thursdays-activities-home.php", "Friday" => "/home/josull05/htdocs/wdd4/php/main-content/fridays-activities-home.php", "Saturday" => "/home/josull05/htdocs/wdd4/php/main-content/saturdays-activities-home.php"

);   include $content[$today];  

1

There are 1 answers

1
Nilambar Sharma On BEST ANSWER

You can try following snippet.

$today = date( 'l' );
$file = '/home/josull05/htdocs/wdd4/php/main-content/' . strtolower( $today ) . 's-activities-home.php';
include( $file );

Variable $today will get day name like Sunday,Monday. In the file name we need day name in small, so strtolower is used.

Note: It will be safe to check existence of file before inclusion. You can use file_exists.