php 如何避免未定义的偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6576313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:46:18  来源:igfitidea点击:

How to avoid undefined offset

php

提问by clarkk

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?

爆炸返回的值并不总是两个,但是如果您想使用 list() ,那么如何轻松避免通知?

回答by KingCrunch

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 nulluntil the array contains 2 values. See Manual: array_pad()for further information
  • 它将返回的数组的大小限制explode()为 2。似乎只需要这个
  • 如果返回的值少于两个,则追加null直到数组包含 2 个值。有关详细信息,请参阅手册:array_pad()

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 $funcand $field

这意味着,如果没有|in $value, $field === null。当然,您可以使用您喜欢定义的每个值作为默认值$field(而不是null)。它也可以交换的行为$func$field

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

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

现在$funcnull,当没有|in 时$value

回答by Jon

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 notto be able to do this, you may want to consider a sneaky indirect approach:

不过,既然不能做到这一点真的很可惜,你可能要考虑一种偷偷摸摸的间接方法:

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

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

我根据需要附加了$value尽可能多的|s,以确保explode在数组中至少产生 2 个项目。对于n变量,添加n-1分隔符。

This way you won't get any errors, you keep the convenient listassignment, 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.

这样你就不会得到任何错误,你保持方便的list分配,并且输入中不存在的任何值都将被设置为空字符串。对于大多数情况,后者不应该给您带来任何问题,因此上述想法会起作用。

回答by Hyman Franklin

You get an undefined offsetwhen the thing you're trying to explode the string by ($value) doesn't actually have it in, I believe.

我相信,undefined offset当您尝试通过 ( $value)来分解字符串的东西实际上并没有包含它时,您会得到一个。

This question is very much similar to this: undefined offset when using php explode(), where there is a much further explanation which should fully solve your issue.

这个问题与此非常相似: undefined offset when using php purge(),其中有更进一步的解释可以完全解决您的问题。

As for checking for the occurrence of '|' as to prevent the error, you can do:

至于检查'|'的出现 为了防止错误,您可以执行以下操作:

$pos = strpos($value,'|');

if(!($pos === false)) {
     //$value does contain at least one |
}

Hope this helps.

希望这可以帮助。

回答by Delmo

This worked for me:

这对我有用:

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

回答by Andreas Jansson

I'd probably break this up into two steps

我可能会把它分成两步

$split = explode('|', $value);
$func = $split[0];
if(count($split) > 1)
  $field = $split[1];
else
  $field = NULL;

There's probably a quicker and neater way though.

不过,可能有一种更快更整洁的方法。

回答by Dennis Crane

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

However it's slightly not optimal.

然而,它稍微不是最佳的。

回答by xtempore

I often come across this issue, so I wanted a function that allowed something nicer syntactically without unnecessarily padding the array or string.

我经常遇到这个问题,所以我想要一个函数,它允许更好的语法,而无需不必要地填充数组或字符串。

// Put array entries in variables. Undefined index defaults to null
function toVars($arr, &...$ret)
{
    $n = count($arr);
    foreach ($ret as $i => &$r) {
        $r = $i < $n ? $arr[$i] : null;
    }
}

// Example usage
toVars(explode('|', $value), $func, $field);

For my purposes, I'm usually working with an array, but you could write a similar function that includes the explode function, like this...

出于我的目的,我通常使用一个数组,但您可以编写一个包含爆炸函数的类似函数,如下所示...

// Explode and put entries in variables. Undefined index defaults to null
function explodeTo($delimiter, $s, &...$ret)
{
    $arr = explode($delimier, $s);
    $n = count($arr);
    foreach ($ret as $i => &$r) {
        $r = $i < $n ? $arr[$i] : null;
    }
}

// Example usage
toVars('|', $value, $func, $field);

Requires PHP5.6 or above for variadic function: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

可变参数函数需要 PHP5.6 或以上版本:http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

回答by Slawa

Want to mention a more general utility function that I use since decades. It filters out empty values and trims spaces. It also uses array_pad()to make sure you get at least the requested amount of values (as suggested by @KingCrunch).

想提一个我几十年来一直在使用的更通用的效用函数。它过滤掉空值并修剪空格。它还用于array_pad()确保您至少获得所需数量的值(如@KingCrunch 所建议的那样)。

/**
 * Does string splitting with cleanup.
 * Added array_pad() to prevent list() complaining about undefined index
 * @param $sep string
 * @param $str string
 * @param null $max
 * @return array
 */
function trimExplode($sep, $str, $max = null)
{
    if ($max) {
        $parts = explode($sep, $str, $max); // checked by isset so NULL makes it 0
    } else {
        $parts = explode($sep, $str);
    }
    $parts = array_map('trim', $parts);
    $parts = array_filter($parts);
    $parts = array_values($parts);
    $parts = array_pad($parts, $max, null);
    return $parts;
}