Auto generate year session

Go to solution Solved by Barand,

Recommended Posts

Hi all

I am trying to create something like 2023-2024 in a loop so that each year it generate the session for me. I don't want to manually add it. What I did did not work (though I know it won't work but just did it anyway)

```\$cur_yr = date('Y');
\$nxt_yr = date('Y', strtotime('+1 year,);
\$cur_session = \$cur_yr."-".\$nxt_yr;

\$strt_session = "2020-2021";

for(\$i = \$strt_session; \$i<= \$cur_session; \$i++){
echo \$i;
}```

Mine won't work. But how can I get it done.

Thanks in anticipation

Edited by I-AM-OBODO
Share on other sites

• Solution

Try this. You don't need date arithmetic for years.

```\$start = 2020;
\$end   = 2029;

for (\$y=\$start; \$y<=\$end; \$y++) {
\$session = sprintf('%d-%d', \$y, \$y+1);
echo \$session . '<br>';
}```

output

```2020-2021
2021-2022
2022-2023
2023-2024
2024-2025
2025-2026
2026-2027
2027-2028
2028-2029
2029-2030```

Share on other sites

I found a way around to get it done as well.

```\$startYear = 2020;
\$endYear = 2024;

for(\$year = \$startYear; \$year <= \$endYear; \$year++){
\$nextYear = \$year + 1;
echo "<option value='\$year-\$nextYear'>\$year-\$nextYear</option>";
}```

Share on other sites

21 minutes ago, Barand said:

Try this. You don't need date arithmetic for years.

```\$start = 2020;
\$end   = 2029;

for (\$y=\$start; \$y<=\$end; \$y++) {
\$session = sprintf('%d-%d', \$y, \$y+1);
echo \$session . '<br>';
}```

output

```2020-2021
2021-2022
2022-2023
2023-2024
2024-2025
2025-2026
2026-2027
2027-2028
2028-2029
2029-2030```

How can it be read from bottom, that is 2027-2028 be at the top? What is order by alternative in php

Share on other sites

`for (\$year = \$endYear; \$year >= \$startYear; \$year--)`

Share on other sites

Oops! In reverse! Thank you so much

Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.