Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid undefined offset

Tags:

php

How can you easily avoid getting this error/notice:

Notice: Undefined offset: 1 in /var/www/page.php on line 149 

... in this code:

list($func, $field) = explode('|', $value); 

There are not always two values returned by explode, but if you want to use list() how can you then easily avoid the notice?

like image 645
clarkk Avatar asked Jul 04 '11 21:07

clarkk


People also ask

How can we avoid undefined index?

The error can be avoided by using the isset() function. This function will check whether the index variables are assigned a value or not, before using them.

What is an undefined offset?

The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.

How do I fix Undefined offset 0 in PHP?

You can do an isset() : if(isset($array[0])){ echo $array[0]; } else { //some error? }

How define offset in PHP?

It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.


2 Answers

list($func, $field) = array_pad(explode('|', $value, 2), 2, null); 

Two changes:

  • It limits the size of the array returned by explode() to 2. It seems, that no more than this is wanted
  • If there are fewer than two values returned, it appends null until the array contains 2 values. See Manual: array_pad() for further information

This means, if there is no | in $value, $field === null. Of course you can use every value you like to define as default for $field (instead of null). Its also possible to swap the behavior of $func and $field

list($func, $field) = array_pad(explode('|', $value, 2), -2, null); 

Now $func is null, when there is no | in $value.

like image 101
KingCrunch Avatar answered Oct 12 '22 13:10

KingCrunch


I don't know of a direct way to do this that also preserves the convenience of

list($func, $field) = explode('|', $value); 

However, since it's really a pity not to be able to do this, you may want to consider a sneaky indirect approach:

list($func, $field) = explode('|', $value.'|'); 

I have appended to $value as many |s as needed to make sure that explode will produce at least 2 items in the array. For n variables, add n-1 delimiter characters.

This way you won't get any errors, you keep the convenient list assignment, and any values which did not exist in the input will be set to the empty string. For the majority of cases, the latter should not give you any problems so the above idea would work.

like image 28
Jon Avatar answered Oct 12 '22 14:10

Jon