Forrar
Forrar

Reputation: 35

PHP echoing out 3 different months (the last one shows wrong)

trying to echo 3 months into my WordPress website according to the todays month. 1) This month 2) Next month 3) Third month.

I have an array with names of the months:

$months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
];

To print out current month:

<?php echo $months[(int)date('m')-1]; ?>

To print out next month:

<?php echo $months[((int)date('m') == 12 ? 1 : (int)date('m') + 1)-1]; ?>

Both if these work just fine. But when I try to print out third month instead of January I get February. Could you help me figure out why?

<?php echo $months[((int)date('m') == 11 ? 1 : (int)date('m') == 12 ? 2 : (int)date('m') + 2)-1]; ?>

I get the answer 0, so it should be January, but seems that

(int)date('m') == 12 ? 2

part is executed, instead of the first one.

Upvotes: 2

Views: 60

Answers (3)

afk
afk

Reputation: 123

You might want to check out the strtotime function in combination with the date function:

<?php
echo date("F", strtotime("first day of +1 month"));

If you want to localize the month-names you could change the first date-parameter to n which gives you the numeric representation of the month and could then be a key to your array.

This might be an easier and more readable solution to your problem.

Upvotes: 1

teeyo
teeyo

Reputation: 3755

The easiest way is to do this using PHP built-in date functions, I mean why reinventing the wheel?

$now = date('Y-m-1');
echo date('m');
echo date('m', strtotime($now . ' + 1 month'));
echo date('m', strtotime($now. ' + 2 month'));

Upvotes: 1

IsThisJavascript
IsThisJavascript

Reputation: 1716

Likely because your ternary operator is evaluating incorrectly.
You also don't need to cast to integer because php does that for you.

echo $months[(date('m') == 11 ? 1 : (date('m') == 12 ? 2 : date('m') + 2))-1];

Outputs: January.

See the change I made? I added () around date('m') == 12 ? 2 : date('m') + 2

Upvotes: 1

Related Questions