tags:

views:

1144

answers:

4

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];

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!

+1  A: 

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.

Dominic Rodger
+1  A: 

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

lallous
Makes sense, but I'd rather find a way of fixing the problem rather than supressing the errors. Thanks though for explaining the cause!
musoNic80
A: 

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?

Ben Fransen
you might want to turn on error reporting
stereofrog
with print_r i'm getting a normal array..
Ben Fransen
+3  A: 

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 ");
stereofrog
+1 for the use of `list()`.
jensgram
That's great. I didn't realise I could put a variable inside quotes. Also, thanks for the bonus 'list()' tip.
musoNic80