CodeBlanks Logo Icon CodeBlanks

Returning arrays from functions

PHP course · Beginner · Lesson 75/116

Learn to return an array from a function and use the result.

Returning arrays from functions

A function can return an array instead of a single value. Example: function bounds() { return [10, 99]; }. You can assign the call result to a variable and reach items with $r[0], $r[1].

This is the easiest way to send several values out at once. You can also loop over the returned array with foreach.

Destructuring arrays with list

To spread a returned array into variables in one go, use list(). Example: list($low, $high) = bounds();. This line puts the first item into $low and the second into $high.

This technique is called destructuring and is a short way to pick up several returned values cleanly.

Exercise Return bounds and destructure them

Define a parameterless function named getBounds. In the body, write return [10, 99];. Then spread the items with list($low, $high) = getBounds(); and print with echo $low . "-" . $high . "\n";.

Show example solution
Write function getBounds() { return [10, 99]; }, then list($low, $high) = getBounds(); and echo $low . "-" . $high . "\n";.
Example solution:
<?php
// Define getBounds and use list to destructure
function getBounds() {
    return [10, 99];
}
list($low, $high) = getBounds();
echo $low . "-" . $high . "\n";

Test yourself

  1. Complete the array return statement

    function bounds() {
        ____ [10, 99];
    }
    $r = bounds();
    echo $r[0];
    Show answer
    function bounds() {
        return [10, 99];
    }
    $r = bounds();
    echo $r[0];
  2. Match array return patterns

    return [10, 99]
    Returns an array
    $r[0]
    Gives first item
    list($a, $b) = ...
    Spreads into variables
  3. What is the output of the code below?

    function bounds() {
        return [10, 99];
    }
    $r = bounds();
    echo $r[1];
    • 10
    • 99
    • [10, 99]
    • 1099
    Show answer

    99 — Correct. $r[1] is the second item, which is 99.

All lessons in Beginner