DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Easily assign variable when using explode in PHP

I use explode all the time, for splitting strings into parts. I typically write my explodes like this:

//set the string
$name = 'Joe Bloggs';

//explode where there is a space
$parts = explode(' ', $name);

//add the parts to variables
$firstName = $parts[0];
$lastName = $parts[1];
Enter fullscreen mode Exit fullscreen mode

But I've recently found out you can assign variables during the explode. Really handy!

This is how do you do it. Using an array to specify the name variables then assign them a value from explode:

//set the string
$name = 'Joe Bloggs';

//explode where there is a space and assign the indexes to named variables
[$firstName, $lastName] = explode(' ', $name);

Enter fullscreen mode Exit fullscreen mode

A must cleaner way in my opinion.

Top comments (0)