Reputation: 3852
I've thought about this problem before but never got anywhere on it. I think I've done it with Python but never PHP.
Define a basic 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>";
}
This is so common, I must have done it a million times during my php career...but it seems a bit wasteful. $row is a temp variable and is never really used and the list()= line seems like it should be able to be put into the foreach bracket
Something like this (of course, this doesn't work):
foreach ($arr as list($a, $b, $c) = $row)
{
echo "$a, $b, $c <br>";
}
Neither does:
foreach ($arr as list($a, $b, $c))
{
echo "$a, $b, $c <br>";
}
Has anyone come up with a cool shortcut for this? Thanks!
Upvotes: 3
Views: 149
Reputation: 146310
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's 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>
Upvotes: 1
Reputation: 14824
Yes, kind of. Use this:
while( list( $key, list( $a, $b, $c ) ) = each( $array ) ) {
// do stuff here
}
Note the use of list
twice - each
returns the key-value pair, and the value is also an array so we use list
again.
You can also use list( , list( $a, $b, $c ) )
, leaving out $key
if you want. But I think that's kind of ugly syntax. ;)
Upvotes: 3
Reputation: 1335
While this will not embed list into foreach, another approach you can find is to use for instead of foreach, and that way, bypassing the temporal variable this way:
$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've added 2 variables more, but they contain only integer, which definitelly reduces memory usage by removing the temporal variable which will contain an array.
Upvotes: 1