6.8. Skipping Selected Return Values
Problem
A function returns multiple values, but you only care about some of them.
Solution
Omit variables inside of list( )
:
// Only care about minutes function time_parts($time) { return explode(':', $time); } list(, $minute,) = time_parts('12:34:56');
Discussion
Even though it looks like there’s a mistake in the
code, the code in the Solution is valid PHP. This is most frequently
seen when a programmer is iterating through an array
using
each( )
, but cares only about the array values:
while (list(,$value) = each($array)) { process($value); }
However, this is more clearly written using a
foreach
:
foreach ($array as $value) { process($value); }
To reduce confusion, we don’t often use this
feature, but if a function returns many values, and you only want one
or two of them, this technique can come in handy. One example of this
case is if you read in fields using fgetcsv( )
, which returns an array holding the
fields from the line. In that case, you can use the following:
while ($fields = fgetcsv($fh, 4096)) { print $fields[2] . "\n"; // the third field }
If
it’s an internally written function and not
built-in, you could also make the returning array have string keys,
because it’s hard to remember, for example, that
array element 2 is associated with 'rank'
:
while ($fields = read_fields($filename)) { $rank = $fields['rank']; // the third field is now called rank print "$rank\n"; }
However, here’s the most efficient method:
while (list(,,$rank,,) ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.