Reputation: 989
Can anybody provide an example of when php's list() function is actually useful or preferable over some other method? I honestly can't think of a single reason I'd ever actually want/need to use it..
Upvotes: -1
Views: 107
Reputation: 47894
When it comes to unpacking array data into variables, there are no features which the "language construct" list()
has, but square braced array destructuring doesn't.
So, no, there is no compelling reason to have list()
anywhere in a project where square braced destructuring is available.
In fact, square braced array destructuring can enjoy the use of the spread operator which list()
cannot.
Upvotes: 0
Reputation: 48284
It's a handy function when you know the right hand side is returning an indexed array of a certain size.
list($basename, $ext) = explode('.', 'filename.png');
Note that it can be used in PHP 5.5 with foreach:
$data = [
['a1', 'b1'],
['a2', 'b2'],
];
foreach ($data as list($a, $b))
{
echo "$a $b\n";
}
But if you prefer more verbose code, then I doubt you'll think the above is "better" than the alternatives.
Upvotes: 0
Reputation: 531
Got a simple sql result row (numeric), containing, say, an ID and a name? A simple solution to deal with it, can be:
list($id,$name)=$resultRow;
Edit; or here's another: you want to know the current key/value pair of an array list($key,$val)=each($arr);
this can even be put into a loop
while (list($key,$val)=each($arr))
altho you could say a foreach is exactly this; but if the $arr changes in the meantime, well then it's not. It has its uses. :)
Upvotes: 1