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!