Home > Enterprise >  Add one year to the date in each 3 iterations
Add one year to the date in each 3 iterations

Time:10-24

I have an array of 6 elements, I would like to add one year after each 3 iterations

This is my array:

$lang = ["PHP", "JAVA", "Ruby", "C", "C  ", "Perl"];

I tried :

$date = Carbon::now();
$i = 0;
foreach($lang as $l){
    if($i % 2 == 0){
       $date = $date->addYear();
    }
   $i  ;
}

CodePudding user response:

There is no problem in your code. You can just edit it to i > 0 to prevent it from running at startup. Since I don't know the Carbon class, I can speculate that date is a class in the beginning, but you may be equating it to a date in your loop. So you can try this:

$date = Carbon::now();
$myDate = '';
$i = 0;
foreach($lang as $l){
    if($i > 0 && $i % 2 == 0){
       $date->addYear();
    }
   $i  ;
}

$myDate = $date->year();

print_r($myDate);
  •  Tags:  
  • php
  • Related