faqts : Computers : Programming : Languages : PHP : kms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

39 of 57 people (68%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do you return an array from a function?

Dec 13th, 2002 01:03
Philip Olson, Kris Erickson, Jonathan Kop,


Returning an array is like returning any other type of variable in 
PHP.  They work great as parameters too.  Here's an example:
function add_fruit($a, $b) {
    return array($a, $b, 'cranberry');
}
$fruits = add_fruit('apple','banana');
foreach ($fruits as $key => $fruit) {
    print "$key : $fruit <br>";
}
    0 : apple <br>
    1 : banana <br>
    2 : cranberry <br>
You can also use use 'global' to make variables (such as arrays) 
available outside the scope of the function.  So:
function foo() {
    global $bar;
    $bar = array('a','b');
}
foo();
print $bar[0]; // a
See also:
    http://www.php.net/return
    http://www.php.net/language.variables.scope.php
    http://www.php.net/types.array
    http://www.php.net/foreach