Multiple Return Values in PHP

In PHP, we can define functions that return multiple values using an array. Here’s an example demonstrating this concept:

<?php

// This function returns an array with 2 integer values
function vals() {
    return [3, 7];
}

function main() {
    // Here we use array destructuring to assign the returned values
    [$a, $b] = vals();
    echo $a . "\n";
    echo $b . "\n";

    // If you only want a subset of the returned values,
    // you can ignore some values using list()
    [, $c] = vals();
    echo $c . "\n";
}

main();

In this example, the vals() function returns an array with two integer values. This is PHP’s way of returning multiple values from a function.

In the main() function, we demonstrate how to use these multiple return values:

  1. We use array destructuring to assign both returned values to variables $a and $b.
  2. We then print these values.
  3. To demonstrate how to use only a subset of the returned values, we use array destructuring again, but this time we ignore the first value by leaving its position empty in the destructuring assignment.

To run this program, save it as multiple_return_values.php and use the PHP command:

$ php multiple_return_values.php
3
7
7

While PHP doesn’t have built-in support for multiple return values in the same way as some other languages, using arrays to return multiple values is a common and idiomatic approach in PHP programming.