PHP:explode()中的未定义偏移量 [英] PHP: undefined offset in explode()

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

问题描述

我有这个:

list($firstname, $lastname) = explode(' ', $queryString);

某些$ lastname未被定义,并且在那里我收到未定义的偏移量错误.

Sometiems $lastname does not gets defined, and it's there i am getting undefined offset error.

我猜是因为找不到$ lastname中的任何内容.

Because it can not find anything to put in $lastname, i guess.

在explode()之后,我有:

After the explode() i have:

if(!$lastname) { $lastname = $firstname; }

所以我的问题是,如果未定义$ lastname,我如何将其定义为$ firstname(如果您只写了'Adam'而不是'Adam Thompson',则应定义姓氏,以便它是'Adam Adam')

So my question is how can i define it as the $firstname if $lastname is not defined (if you wrote only 'Adam' and not 'Adam Thompson', the lastname should be defined so it is 'Adam Adam')

它现在为我执行此操作,但是我收到偏移错误

It does this for me now, but I am receiving the offset error

推荐答案

list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, null);

explode()中的2确保最多存在 2个值,而array_pad()确保至少存在 2个值.如果没有空格字符,则$lastnamenull.您可以使用它来确定接下来要做什么

The 2 in explode() ensures, that there are at most 2 values and array_pad() ensures, that there are at least 2 values. If there is no space character , $lastname is null. This you can use to decide what comes next

$lastname = is_null($lastname) ? $firstname : $lastname;

少量更新:对于这种特定情况,您可以使用一些技巧

Little update: For this specific case you can use a little trick

list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, $queryString);

这将一步一步完成所有操作.应该可以,因为

This will do all that in one step. It should work, because

  • 始终至少有一个值(对于$firstname)
  • 如果有一个值,则为$queryString == $firstname.多数民众赞成现在用于填充数组的值最多为2个值(正好是一个,因为我们已经有一个值)
  • 如果有两个值,则数组未填充$queryString,因为我们已经有2个值
  • There is always at least one value (for $firstname)
  • If there is one value, then $queryString == $firstname. Thats now the value that is used to fill the array up to 2 values (which is exactly one, because one value we already have)
  • If there are two values, then the array is not filled with $queryString, because we already have 2 values

至少出于可读性考虑,我更喜欢第一个更明显的解决方案.

At least for readability I would prefer the first more obvious solution.

这篇关于PHP:explode()中的未定义偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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