如何避免未定义的偏移 [英] How to avoid undefined offset

查看:109
本文介绍了如何避免未定义的偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松避免出现此错误/通知:

How can you easily avoid getting this error/notice:

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

...在此代码中:

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

explode不一定总是返回两个值,但是如果您想使用list(),那么如何轻松地避免该通知呢?

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

推荐答案

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

两项更改:

  • 它将explode()返回的数组的大小限制为2.看来,只需要这个就可以了.
  • 如果返回的值少于两个,它将附加null直到数组包含2个值.有关更多信息,请参见手册:array_pad()
  • 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

这意味着,如果$value中没有|,则$field === null.当然,您可以使用要定义为$field(而不是null)默认值的每个值.也可以交换$func$field

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);

$value中没有|时,现在$funcnull.

这篇关于如何避免未定义的偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆