Home » Php » php – How to avoid Undefined offset error?

php – How to avoid Undefined offset error?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

Assumes that at least one will always exist

$data = 'a-b';

list($one, $two, $three) = explode("-", $data . '-0-0');

Answer:

You need to use isset. Isset check if the variable exists.

// You can get rid of this since we set the default later if isset fail
/*
$one = 0;
$two = 0;
$three = 0;
*/

$data = 'a-b-c';

$data = explode('-', $data);
$one = (isset($data[0]) === TRUE ? $data[0] : 0);
$two = (isset($data[1]) === TRUE ? $data[1] : 0);
$three = (isset($data[2]) === TRUE ? $data[2] : 0);

Answer:

by using isset like isset($data[0] == true)

Answer:

I usually do like this:

$a = array(1,2,3,4);
$current = 0;
$index = 0;
while(isset($a[$index])) {
    $current = $a[$index];
    //... do something ...
    $index++;
}

This works!