Skip to content
Advertisement

Why is today`s weekday pluss two not working?

Any reason why $daynames[$dayW +1] works and displays todays dayname +1, but not $daynames[$dayW +2]? I am trying to display days in the week +1 day in the first and +2 days in the second cell, but I get an error on the +2 line.

$daynames = array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag");

$dayW = date("w");

<td><?php echo $daynames[$dayW];?></td>
<td><?php echo $daynames[$dayW +1];?></td>
<td><?php echo $daynames[$dayW +2];?></td>
<td><?php echo $daynames[$dayW +3];?></td>
<td><?php echo $daynames[$dayW +4];?></td>
<td><?php echo $daynames[$dayW +5];?></td>
<td><?php echo $daynames[$dayW +6];?></td>

Advertisement

Answer

I guess you’re trying to print what is the day name when you add a number of days to a given day right ? If true, I think you might need to look for the modulo function (cf. https://www.php.net/manual/fr/language.operators.arithmetic.php) Basically here, the principle is that every time you add 7 days, you get the same day name; so you need a modulo 7.

Here is your code slightly altered to show this in action :

<?php

$daynames = array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag");

$dayW = date("w");



echo "## 1) First method : just tweaking your code" . PHP_EOL . PHP_EOL;
echo $daynames[$dayW % 7] . PHP_EOL;
echo $daynames[($dayW +1) % 7] . PHP_EOL;
echo $daynames[($dayW +2) % 7] . PHP_EOL;
echo $daynames[($dayW +3) % 7] . PHP_EOL;
echo $daynames[($dayW +4) % 7] . PHP_EOL;
echo $daynames[($dayW +5) % 7] . PHP_EOL;
echo $daynames[($dayW +6) % 7] . PHP_EOL;

You can also see that in action here https://3v4l.org/6daZo with another slightly sophisticated variation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement