We help IT Professionals succeed at work.

Could you point  how to handle Undefined Offset Error in Laravel?

Eduardo Fuerte
on
Hi Experts

Could you point  how to handle Undefined Offset Error in Laravel?

This code:

        $registros = array();

        for($indexDistribuidor = 0; $indexDistribuidor<count($metas); $indexDistribuidor += 12){
            $item = array();
            array_push($item, $metas[$indexDistribuidor]->razaosocial);
            array_push($item, $metas[$indexDistribuidor]->cnpj);
            for($indexMes = 0; $indexMes < 12; $indexMes++){
                array_push($item, $metas[$indexDistribuidor + $indexMes]->meta);
            }

            array_push($item, $metas[$indexDistribuidor]->distribuidor_id);
            array_push($item, $ano);

            array_push($registros, $item);
        }

        return $registros;
		

Open in new window


During the foreach the array of objects is correctly been mounted.

But at certain point this offset error is produced:

 img004
Any workaround?

Thanks in advance.
Comment
Watch Question

Bhavesh ShahLead Analyst
CERTIFIED EXPERT
Top Expert 2010

Commented:

hi,


you can fix this using isset().


did you try it?

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
Hey Eduardo,

Because you're looping within a loop, your code can try and access an array index larger than the count, which is why you're getting the error. You need to check it and break out if the index exceeds the count. Something like this should do it:

for($indexMes = 0; $indexMes < 12; $indexMes++){
    if (!isset( $metas[$indexDistribuidor + $indexMes] )) break;
    array_push($item, $metas[$indexDistribuidor + $indexMes]->meta);
}

Open in new window

Now if $indexDistribuidor + $indexMes is an invalid index, the code will break out of the for loop and continue with the code after it
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi Chris

By using your code the error doesn't occurs at controller but  now  is occurring at view...



It's due 12 months possible to present data at view.

The previous query that must to generate data have to be adjusted to get only 12 lines per "distribution company".
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Really

After correcting the query everything is OK.

But your suggestion is pretty good.

Thank you!