Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Undefined offset error?

Tags:

php

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?

like image 789
tfe Avatar asked Jun 30 '13 12:06

tfe


2 Answers

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.

like image 90
ChrisG Avatar answered Sep 23 '22 04:09

ChrisG


Assumes that at least one will always exist

$data = 'a-b';

list($one, $two, $three) = explode("-", $data . '-0-0');
like image 23
Mark Baker Avatar answered Sep 21 '22 04:09

Mark Baker