Is it possible to inline a list function in a foreach statement in PHP?
I've thought about this issue before but haven't found it anywhere. I think I have done this with Python, but never PHP.
Define a base php array:
$arr = array (array(1,2,3), array(4,5,6), array(7,8,9));
Then run this snippet:
foreach ($arr as $row)
{
list($a, $b, $c) = $row;
echo "$a, $b, $c <br>";
}
It's so common, I've had to do this a million times during my php career ... but it seems a little wasteful. $ row is a temporary variable and never used, and the list () = line seems like it should be put in the foreach bracket.
Something like this (of course it doesn't work):
foreach ($arr as list($a, $b, $c) = $row)
{
echo "$a, $b, $c <br>";
}
Also:
foreach ($arr as list($a, $b, $c))
{
echo "$a, $b, $c <br>";
}
Has anyone come up with a cool shortcut for this? Thank!
source to share
Yes, sort of. Use this:
while( list( $key, list( $a, $b, $c ) ) = each( $array ) ) {
// do stuff here
}
Note the use list
twice - each
returns a key-value pair and that value is also an array, so we use again list
.
You can also use list( , list( $a, $b, $c ) )
by leaving $key
if you like. But I think this ugly syntax.;)
source to share
You can try this:
$array = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) );
for($next = current($array), list($a, $b, $c) = $next;
// ^ current array ^ current list
$next;
// ^ check if array
$next = next($array), list($a, $b, $c) = $next)
// ^ next array ^ next array list
{
echo "$a, $b, $c <br>".PHP_EOL;
}
Demo: http://codepad.org/cuYl6iaa
Output:
1, 2, 3 <br>
4, 5, 6 <br>
7, 8, 9 <br>
source to share
While this will not include the list in foreach, another approach you may find is to use foreach instead and thus bypassing the temporary variable like this:
$a = array (array(1,2,3), array(4,5,6), array(7,8,9));
$count=(int)count($a);
for ($i=(int)0; $i<count; $i++) {
list($a, $b, $c)=$a[$i];
echo "$a, $b, $c<br />";
}
With this I added 2 more variables, but they only contain an integer which definitely reduces memory usage by removing the temporary variable that will contain the array.
source to share