使用php explode()时未定义的偏移量 [英] undefined offset when using php explode()

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

问题描述

我已经写了我认为是对php explode()函数的非常简单的用法,可以将名字分为姓氏和姓氏

I've written what I thought was a very simple use of the php explode() function to split a name into forename and surname:

// split name into first and last
$split = explode(' ', $fullname, 2);
$first = $split[0];
$last = $split[1];

但是,这将抛出php错误,并显示消息"Undefined offset: 1".该功能似乎仍然有效,但是我想清除导致错误的任何原因.我已经检查过 php手册,但是它们的示例使用与以下示例相同的语法以上. 我想我知道什么是未定义的偏移量,但是我看不到我的代码为什么会生成错误!

However, this is throwing up a php error with the message "Undefined offset: 1". The function still seems to work, but I'd like to clear up whatever is causing the error. I've checked the php manual but their examples use the same syntax as above. I think I understand what an undefined offset is, but I can't see why my code is generating the error!

推荐答案

这是因为您的全名不包含空格.您可以使用一个简单的技巧来确保空间始终在其中

this is because your fullname doesn't contain a space. You can use a simple trick to make sure the space is always where

 $split = explode(' ', "$fullname ");

(请注意引号内的空格)

(note the space inside the quotes)

顺便说一句,您可以使用list()函数来简化代码

BTW, you can use list() function to simplify your code

  list($first, $last) = explode(' ', "$fullname ");

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

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