Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined offset when using php explode()

Tags:

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

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!

like image 295
musoNic80 Avatar asked Nov 27 '09 10:11

musoNic80


People also ask

How fix Undefined offset in PHP?

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.

How does explode work in PHP?

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.

What is undefined offset 1?

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.

What does the explode () function do?

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.


2 Answers

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 ");
like image 56
user187291 Avatar answered Oct 23 '22 18:10

user187291


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

like image 29
phse Avatar answered Oct 23 '22 17:10

phse