3
\$\begingroup\$

I have an event recurring on the first friday of the month (at 7pm), and I need to output the date of the next first friday coming up.

This is the first bit of PHP I've written, and I was wondering if there is a better way to implement this? Server is running PHP 5.3

Here's what I wrote:

$todays_date = strtotime('today');
$first_friday = strtotime('first friday of this month');
if ($todays_date > $first_friday) {
 $next_month = date('M j', strtotime('first friday of next month'));
 echo 'Friday, '.$next_month;
} elseif ($todays_date == $first_friday) {
 echo 'Today';
} else {
 $this_month = date('M j', strtotime('first friday of this month'));
 echo 'Friday, '.$this_month;
}

And here is a suggested improvement offered by someone else, which also introduced me to ternary operators:

$today = new DateTime();
$this_months_friday = new DateTime('first friday of this month');
$next_months_friday = new DateTime('first friday of next month');
echo ($today < $this_months_friday) ? 'Friday, '.$this_months_friday->format('M j').' at 7pm' : 'Friday, '.$next_months_friday->format('M j').' at 7pm';

I had looked all over for a short way to do this and was only running into very large and complicated answers. Both my way and the answer provided by someone else are much much shorter and more readable.

asked Jan 23, 2013 at 23:18
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can improve your ternary operator by using it like this :

$today = new DateTime();
$this_months_friday = new DateTime('first friday of this month');
$next_months_friday = new DateTime('first friday of next month');
echo 'Friday, '. (($today < $this_months_friday) ? $this_months_friday->format('M j') : $next_months_friday->format('M j')) . ' at 7pm';

which can them become :

echo 'Friday, '. (($today < $this_months_friday) ? $this_months_friday : $next_months_friday)->format('M j') . ' at 7pm';
answered Jan 24, 2013 at 1:15
\$\endgroup\$
3
  • \$\begingroup\$ Concatenating the ternary operator onto the string was causing some strange behavior when I was testing the improved version. What you wrote there works as expected. Thank you! \$\endgroup\$ Commented Jan 24, 2013 at 5:16
  • \$\begingroup\$ You're welcome. Perhaps were you missing parenthesis ? \$\endgroup\$ Commented Jan 24, 2013 at 6:34
  • \$\begingroup\$ That was the problem all along. It was evaluating the whole string when I didn't have the parenthesis in there. Thanks @Josay! \$\endgroup\$ Commented Jan 24, 2013 at 19:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.