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?
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.
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.
You can do an isset() : if(isset($array[0])){ echo $array[0]; } else { //some error? }
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.
list($func, $field) = array_pad(explode('|', $value, 2), 2, null);
Two changes:
explode()
to 2. It seems, that no more than this is wantednull
until the array contains 2 values. See Manual: array_pad() for further informationThis 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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With