Using list() with foreach() in PHP

Josh Sherman
2 min read
Software Development PHP

Continuing my showcasing of all of the awesomeness in PHP 5.5 that I am discovering since my upgrade from 5.3, let’s discuss using the the list() function inside of a foreach() block.

Have you ever had a situation where you are looping through a multi-dimensional array and the array is non-associative? If so, you probably have some code that looks like this:

$items = array(
    array('var1', 'var2', 'var3'),
    array('var1', 'var2', 'var3'),
    array('var1', 'var2', 'var3'),
    array('var1', 'var2', 'var3'),
    array('var1', 'var2', 'var3'),
);

foreach ($items as $item)
{
    list($var1, $var2, $var3) = $item;

    if ($var1 == $var2)
    {
        echo $var3;
    }
}

Or even worse, you’re not even using the list() function:

foreach ($items as $item)
{
    $var1 = $item[0];
    $var2 = $item[1];
    $var3 = $item[3];

    if ($var1 == $var2)
    {
        echo $var3;
    }
}

Or worse than that, lacking any sort of variable mapping / meaningful references to the variables:

foreach ($items as $item)
{
    if ($item[0] == $item[1])
    {
        echo $item[2];
    }
}

NO LONGER! as now you can leverage the assignment power of list() right inside of your foreach() statement:

foreach ($items as list($var1, $var2, $var3))
{
    if ($var1 == $var2)
    {
        echo $var3;
    }
}

I haven’t run any benchmarks to see if this is any faster or slower than using list() inside of the block itself instead of in the statement, but to me it’s worth a small bit of overhead for the cleanliness of the code when dealing with a small number of arguments.

What’s your preferred method? Comment below!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles