Error with arrays - Undefined offset: 2 in Laravel PHP

0

I have a problem trying to save arrays in a table in my database.

I have the code in this way in the store() function of my controller:

try {
  foreach($request->horario as $id_horario=>$row){  
    foreach($row['check'] as $check){

        $startdate = $row['desde'];
        $endate = $row['hasta'];

        $period = CarbonPeriod::create($startdate, $endate);
        $period_2 = CarbonPeriod::create($startdate, $endate);

        $dates = $times = [];
        $dates_2 = $times_2 = [];

        $tstart = Carbon::createFromFormat('H:i:s', $row['hora_inicio']);
        $tend = Carbon::createFromFormat('H:i:s', $row['hora_termino']);

        $tstart_2 = Carbon::createFromFormat('H:i:s', $row['hora_inicio']);
        $tstart_2->modify('+1 hour');

        $tend_2 = Carbon::createFromFormat('H:i:s', $row['hora_termino']);

        while ($tstart < $tend){
            $times[] = $tstart->format("H:i:s");
            $tstart->addHour(); // 
        }
        while ($tstart_2 <= $tend_2) {      
            $times_2[] = $tstart_2->format('H:i:s');
            $tstart_2->addHour();
        }
        foreach($period as $date){
            foreach($times as $time){
                $dates[] = $date->format("Y-m-d") . " " . $time;
            }
        }
        foreach ($period_2 as $date_2) {
            foreach ($times_2 as $time_2) {
                $dates_2[] = $date_2->format('Y-m-d'). " ".$time_2;
            }
        }


        $cuenta = count($dates);

        for($i = 0; $i < $cuenta; $i++){

            $horarios[]= [    
                'hora_incio' => $dates[$i],
                'hora_fin' => $dates_2[$i],
                'estado_horario_id' => $row['estado_horario_id'],
                'cancha_id ' => $check
            ];
        }

        /*ESTA PARTE ME ARROJA EL ERROR*/
        HorariosNew::create(['hora_incio' => $dates[$i],'hora_fin' => $dates_2[$i],'estado_horario_id' => $row['estado_horario_id'], 'cancha_id ' => $check]);
        $horarios->save();
    }
  }
}

And the error thrown at me is Undefined offset: 2, I'm not sure why I get that error.

    
asked by M4uriXD 12.12.2018 в 20:30
source

1 answer

1

The line that gives you the error is outside the for therefore it is because it comes out with a value greater than the size of the data array.

This is because it keeps iterating while $i < $cuenta and exits at the moment that $i==$cuenta in your case 2 and the array only has the indexes 0 and 1 .

You can check it out by displaying all the values: $i , $cuenta and $dates

    
answered by 12.12.2018 / 20:41
source