I am trying to create a drop down with just the working days of the week on. Monday - Friday. Here's my code:
<?php if ($_SESSION['month'] == $current_month) { $current_day = date("j") + 1;} else {$current_day = 1;} ?>
<form action="" method="post">
<select name="day" onchange="this.form.submit()">
<option value="">-- Day --</option>
<?php for ($i = $current_day; $i < 31; $i++) { ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
<?php $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i;
$weekday = date('D', strtotime($tmp_date));
echo $weekday." "; ?>
<?php echo $i; ?>
</option>
<?php } ?>
</select>
</form>
This gives me the days of the week for the current month, but it shows all days. How can I only show Monday - Friday?
It looks like $weekday
is getting the names for you. Just do a nocase string compare:
$weekday = date('D', strtotime($tmp_date));
if (strcasecmp($weekday, 'Sun') != 0
&& strcasecmp($weekday, 'Sat') != 0){
// Do something with valid days
}
<?php $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i; ?>
<?php if (!in_array(date('w', strtotime($tmp_date)), array(0, 6)) { ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
$weekday = date('D', strtotime($tmp_date));
echo $weekday." "; ?>
<?php echo $i; ?>
</option>
<?php } ?>
This is a lot clearer then strtotime()
:
$start = DateTime::createFromFormat('Y-n-j', $_SESSION['year'].'-'.$_SESSION['month'].'-01');
$daysInMonth = $start->format('t');
$end = new DateTime("+{$daysInMonth} Days");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $day) {
if (in_array($day->format('D'), array('Sat', 'Sun'))) continue;
printf('<option value="%s"%s>%s %u</option>',
$day->format('j'),
($_SESSION['day'] == $day->format('j')) ? ' selected' : '',
$day->format('D'),
$day->format('j')
);
}
Demo
This works for me:
<form action="" method="post">
<select name="day" onchange="this.form.submit()">
<option value="">-- Day --</option>
<?php for ($i = $current_day; $i < 31; $i++) {
$tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i;
$weekday = date('D', strtotime($tmp_date));
if (strcasecmp($weekday, 'Sun') != 0
&& strcasecmp($weekday, 'Sat') != 0){ ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
<?php echo $weekday." ".$i; ?>
<?php } ?>