Skip to content
Related Articles
Open in App
Not now

Related Articles

How to return multiple values from function in PHP?

Improve Article
Save Article
  • Last Updated : 10 Feb, 2022
Improve Article
Save Article

PHP doesn’t support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed. However, there are ways to work around this limitation. 
The multiple values can be returned from a function by using an array.
Example 1: This example shows how to return multiple values from a function in PHP. First, create an empty array end push the element to the array and then return the array.


// Function to return the array
// of factors of n
function factors( $n ) {
    // Declare an empty array
    $fact = array();
    // Loop to find the
    for ( $i = 1; $i < $n; $i++) {
        // Check if i is the factor of
        // n then push it into array
        if( $n % $i == 0 )
            array_push( $fact, $i );
    // Return the array
    return $fact;
// Declare a variable and initialize it
$num = 24;
// Function call
$nFactors = factors($num);
// Display the result
echo 'Factors of ' . $num . ' are: <br>';
foreach( $nFactors as $x ) {
    echo $x . "<br>";


Factors of 24 are: 


Example 2: This example uses list function to store the swapped value of variable. It is used to assign array values to multiple variables at the same time. The multiple values returned in array from the function can be assigned to corresponding variables using list().


// Function to swap two numbers
function swap( $x, $y ) {
    return array( $y, $x );
// Declare variable and initialize it
$a = 10;
$b = 20;
echo 'Before swapping the elements <br>';
// Display the value of a and b
echo 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>';
// Function call to swap the value of a and b
list($a, $b) = swap($a, $b);
echo 'After swapping the elements <br>';
// Display the value of a and b
echo 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>';


Before swapping the elements 
a = 10
b = 20
After swapping the elements 
a = 20
b = 10


PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!