undefined offset when using php explode()

断了今生、忘了曾经 提交于 2019-11-28 00:42:32

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)

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

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

This could be due the fact that $fullname did not contain a space character.

This example should fix your problem w/o displaying this notice:

$split = explode(' ', $fullname, 2);
$first = @$split[0];
$last = @$split[1];

Now if $fullname is "musoNic80" you won't get a notice message.

Note the use of "@" characters.

HTH Elias

BTW, that algorithm won't work all the time. Think about two-word Latina or Italian surnames names like "De Castro", "Dela Cruz", "La Rosa", etc. Split will return 3 instead of 2 words:

Array {
  [0] => 'Pedro'
  [1] => 'De'
  [1] => 'Castro'
}

You'll end up with messages like "Welcome back Ana De" or "Editing Profile of Monsour La".

Same thing will happen for two-word names like "Anne Marie Miller", "William Howard Taft", etc.

Just a tip.

Presumably, whatever $fullname is doesn't contain a space, so $split is an array containing a single element, so $split[1] refers to an undefined offset.

That' strange, it's working correct here. When i try with a string the cat walks and also just the will do and not produce an error. I've outputted it with print_r

What's your $fullname looks like when you get the error?

Use array_pad

e.q.: $split = array_pad(explode(' ', $fullname), 2, null);

  • explode will split your string into an array without any limits.
  • array_pad will fill the exploded array with null values if it has less than 2 entries.

See array_pad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!