tfe tfe - 1 year ago 47
PHP Question

How to avoid Undefined offset error?

This is a part of my script:

$one = 0;
$two = 0;
$three = 0;

$data = 'a-b-c';

$data = explode("-", $data);
$one = $data[0];
$two = $data[1];
$three = $data[2];

No problems so far but $data sometimes can be

$data = 'a-b-c';

and sometimes

$data = 'a-b';

In case of
$data = 'a-b'
; I get Undefined offset: 3 error. Is it some way how to avoid this error?

Answer Source

Wrap the assignment into an if-block:

if(isset($data[0])) {
    $one = $data[0];


This now checks if this array item isset, if not you just do not assign it and no error will show up.