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.

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.