Home > Mobile >  Increase year after every 3 iterations while looping
Increase year after every 3 iterations while looping

Time:10-24

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(); 
   }
}

CodePudding user response:

Bump the year every time $key is not zero and $key / 3 has no remainder.

Code: (Demo)

$langs = ["PHP", "JAVA", "Ruby", "C", "C  ", "Perl", 'foo', 'bar', 'bam'];
$date = Carbon::now();
foreach ($langs as $key => $lang){
   if ($key && $key % 3 === 0) {
       $date->addYear();
   }
   echo $lang .' - '. $date->format('Y') . PHP_EOL; 
}

CodePudding user response:

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):

$langs = ["PHP", "JAVA", "Ruby", "C", "C  ", "Perl", 'foo', 'bar', 'bam'];
$year = Carbon::now()->year;

foreach ($langs as $key => $lang){
   if ($key && $key % 3 === 0) {
       $year  ;
   }
   echo $lang .' - '. $year . PHP_EOL; 
}
  • Related