skip to Main Content

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


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

    Code: (Demo)

    $langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl", "Perl", "Python", "Javascript", "Mysql"];
    $date = Carbon::now();
    foreach ($langs as $key => $lang){
       if ($key && $key % 3 === 0) {
           $date->addYear();
       }
       echo $lang .' - '. $date->year . PHP_EOL; 
    }
    

    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)

    $langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl", "Perl", "Python", "Javascript", "Mysql"];
    $year = date('Y');
    foreach ($langs as $key => $lang){
       if ($key && $key % 3 === 0) {
           ++$year;
       }
       echo $lang .' - '. $year . PHP_EOL; 
    }
    
    Login or Signup to reply.
  2. 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; 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search