DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

2 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs