8.6 Returning More Than One Value from a Function


You need to return more than one value from a function, but PHP only allows you to return one value.

Technique

Use the array() and list() constructs to return more than one value from a function. These values can be of any PHP-supported type.

 function get_current_date () {     $plain_date = date("m/d/Y");     $fancy_date = date("l, F d, Y");     return array($plain_date, $fancy_date); } list($plain_date, $fancy_date) = get_current_date (); if (user_prefs("fancy"))     print $fancy_date; else     print $plain_date; 

Comments

In PHP, as in C, you cannot legally return more than one value from a function. However, you can return an array of values. In the example, we return an array of values from the get_current_date() function. We then use the list statement to capture the returned values.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net