Easily assign variable when using explode in PHP

David Carr

Tutorials PHP & MySQL

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

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

A must cleaner way in my opinion.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.