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:

<?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.

 

Next chapter: Array-specific functions >>

Previous chapter: The array operator

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar