I have an array contain n
number of elements can be 6 or 8, like that:
$langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl"];
I would like to add one year evenly next to the elements
Desired output in case of 6 elements:
- PHP – 2022
- JAVA – 2022
- Ruby – 2022
- C – 2023
- C++ – 2023
- Perl – 2023
Desired output in case of 9 elements:
- PHP – 2022
- JAVA – 2022
- Ruby – 2022
- C – 2023
- C++ – 2023
- Perl – 2023
- Python – 2024
- Javascript – 2024
- Mysql – 2024
My try :
$date = Carbon::now();
foreach($langs as $key => $lang){
if(count($langs) % $key == 0){
echo $lang .' - '. $date->addYear();
}
}
2
Answers
Bump the year every time
$key
is not zero and$key / 3
has no remainder.Code: (Demo)
To be perfectly honest, I don’t see any benefit is calling a datetime wrapper for this very basic task. You can easily replace all usage of Carbon with PHP’s native
date()
function. (Demo)I’d use
%3
as suggested by @mickmackusa but I would avoid incrementing the year of a date object as here you just need to get the year number and increment it (the month/day/hour/etc. is not an info you need to keep):