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!
Fix Notice: Undefined offset by using isset() Function Check the value of offset array with function isset(), empty(), and array_key_exists() to check if key exist or not.
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.
The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.
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 ");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With