Using PHP’s list() with varying length arrays

Post #9, veröffentlicht am in
  • Web design
  • How to

I enjoy using list() (php.net/manual/en/function.list.php) to disassemble arrays into named variables. It is a bit awkward at first, having a language construct on the left side of the is equal to character (=), but that’s okay.

Say, you want to dismantle a page’s path into named fragments.
This is, what that might look like for only one fragment (like "/contact"):

list(, $level1) = explode('/', $_SERVER['REQUEST_URI']);

The first fragment is always empty, in this case. That is why we ditch it with an empty list element at the front.

The above example is ignorant of any path fragments after the second one ("contact"), though.
For list() elements with explicit keys, one can define defaults. That doesn’t work for elements without keys.
Let’s fix that.

In the following example the page we are looking at is three levels deep.

list(, $level1, $level2, $level3) = explode('/', $_SERVER['REQUEST_URI']);


Unfortunately, if you use this on your contact page, which is only one level deep, listing that one fragment will fail. list() doesn’t like the input array being too short. How can we account for that?

Luckily, list() doesn’t care, if the input array is too long for its elements.
Thus, we can “fill” the array with empty elements at the end:

list(, $level1, $level2, $level3) = explode('/', $_SERVER['REQUEST_URI'] . '//');

Every time you hit a page, that is lower than the three levels, you now get those empty elements filled with empty strings. No errors thrown. Problem solved. ✅

Bonus: Shorthand

As of PHP 7.1 there is a shorthand for the list construct—and you know, I love a good shorthand:

[, $level1, $level2, $level3] = explode('/', $_SERVER['REQUEST_URI'] . '//');