PHP 7.1 introduced a new syntax for the list() function. I've never really seen too much list() calls in the wild, but it enables you to write some pretty neat stuff.

This post is a primer of list() and it's PHP 7.1 short notation, and an overview of some use cases I've been applying them to.

list() 101

The list() construct (it's actually not a function but a language construct like array()) has been around since PHP 4. list() allows you to pull variables from an array based on their index. Let's start with a quick primer!

Voila, nothing too fancy here, let's move over to some more specific use cases, borrowed from other languages.

Exhibit B: Tuples

The most concise definition of a tuple is a “data structure consisting of multiple parts”. Tuples are pretty much arrays with a fixed size and a predefined structure, for example a tuple of a status code and a message, a tuple of a longitude and a latitude, etc.

Tuples are useful in PHP when a key-value pair just doesn't cut it (maybe we need duplicate keys, or would want more that one value) and when we don't want to bother creating a value object.

Let's start with an array of some fruits and vegetables. Every piece of produce has an id, a name and a type.

Using the index to access the values requires us to reason about the array contents on every statement. Though process: “This is $item[0], which means is the first item in the array. Next is $item[1], which means it's the second item, etc."

Exhibit C: Multiple Returns

Some languages allow multiple returns. Consider a function that expects an integer, and returns two integers, one of them being $input + 5, the other $input - 5. Here's what that would look like in Go:

That's It!

That concludes today's presentation. I'll update the post in the future when I come accross other nifty use cases. Meanwhile, feel free to hit me up on Twitter if you're using list() in other cool ways!