undefined offset when using php explode()

后端 未结 7 1887
闹比i
闹比i 2020-12-03 17:07

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 f         


        
相关标签:
7条回答
  • 2020-12-03 17:31

    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.

    0 讨论(0)
  • 2020-12-03 17:32

    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

    0 讨论(0)
  • 2020-12-03 17:35

    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.

    0 讨论(0)
  • 2020-12-03 17:40

    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 ");
    
    0 讨论(0)
  • 2020-12-03 17:44

    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

    0 讨论(0)
  • 2020-12-03 17:44

    array_pad is the only valid answer in this thread, all others are ugly hacks that can explode into your face. With array_pad you can always be sure that the amount of elements is correct and filled. Especially important when using with a list() type output.

    0 讨论(0)
提交回复
热议问题