DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

PHP explode function Magic

Alt Text
I most often use explode function to separate firstname and lastname value from name field to store in the database.

To do so my code looks like below.

$fullName = "John Doe";
$pieces = explode(' ', $fullName);
$firstName = $pieces[0]; // John
$lastName = $pieces[1]; // Doe
Enter fullscreen mode Exit fullscreen mode

But recently working in an project I found an issue with this code when user adds middle name also.

So lets say name is John Jane Doe. Above code saves gives $firstName as 'John' and $lastName as 'Jane' and 'Doe' is missing.

So in finding solution to this I came across solution of explode function in php official documentation.

The solution is pretty simple. explode function accepts third parameter as integer, which limits number of elements in output array.

So my solution code looked like this.

$fullName = "John Jane Doe";
$pieces = explode(' ', $fullName, 2); // only two elements
$firstName = $pieces[0]; // John
$lastName = $pieces[1]; // Jane Doe
Enter fullscreen mode Exit fullscreen mode

Top comments (0)