PHP Functions
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. To reduce confusion, don’t use this feature frequently; but if a function returns many values, and you only want one or two of them, it 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 a user-defined 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,,) = fgetcsv($fh, 4096)) {
print "$rank\n"; // directly assign $rank
}
Be careful you don’t miscount the amount of commas; you’ll end up with a bug.
No comments:
Post a Comment