Returning arrays from functions

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:

    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.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Array-specific functions >>

Previous chapter: The array operator

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.