Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Unpack arrays conditionally in PHP

Array unpacking is a sleek way of assigning the value of array elements to variables in one shot like so.

$user = ['Cherika', 'Merchant'];

[$firstName, $lastName] = $user;

echo $firstName; // Cherika
echo $lastName; // Merchant

Now, there might be a situation where the variable that holds the array could probably be null and so, in such a scenario, you would need to first check this like so.

$user = ['Cherika', 'Merchant'];

if ($user) {
    [$firstName, $lastName] = $user;
}

But recently, I got to know about an elegant way of doing so. i.e to unpack the array directly inside a condition like so.

$user = null;

if ([$firstName, $lastName] = $user) {
    // Won't be reached
}

Pretty sleek, no?

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?