Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays Wish List | Report Bug | About Me ]

5.5     Returning arrays from functions

This is NOT the latest copy of this book; click here for the latest version.

In PHP you can return one and only one value from your user functions, but you are able to make that single value an array, thereby allowing you to return many values.

This following code shows how easy it is:

<?php
    
function dofoo() {
        
$array["a"] = "Foo";
        
$array["b"] = "Bar";
        
$array["c"] = "Baz";
        return
$array;
    }
    
    
$foo = dofoo();
?>

Without returning an array, the only other way to pass data back to the calling script is by accepting parameters by reference and changing them inside the function. Passing arrays by reference like this is generally preferred as it is less of a hack, and also frees up your return value for some a true/false to check whether the function was successful.





<< 5.4 The array operator   5.6 Array-specific functions >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Just Me - 29 Aug 2008

I think he meant "passing arrays by reference is generally preferred to passing arrays as a return value"

A PHP User - 29 Aug 2008

Yes, he meant it's preferred to return values by reference instead of as arrays.

A PHP User - 29 Aug 2008

It makes sense I think, if you read the "a" before "true/false" not as the word "a" but as a variable like "x", meaning any true/false.

A PHP User - 29 Aug 2008

This doesn't seem to jive with the rest of the text:

"Passing arrays by reference like this is generally preferred as it is less of a hack, and also frees up your return value for some a true/false to check whether the function was successful."

Did you mean passing values by reference is generally preferred to passing arrays as a return value?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is three plus ten?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow