Monday 31 May 2021

Php: Return multiple values from a function

In Php, functions return single value. If you have a requirement to return multiple values, you can use either of following approaches.

 

a.   Returning an array from function

b.   Returning an object from the function

 

Returning an array from function

Example

function calc_arithmetic($var1,$var2){
    $sum = $var1 + $var2;
    $sub = $var1 - $var2;
    $mul = $var1 * $var2;
    $div = $var1 / $var2;

    return array(
        'sum'=>$sum,
        'sub'=>$sub,
        'mul'=>$mul,
        'div'=>$div
    );
}

 

Find the below working application.

 

function_return_array_demo.php

#!/usr/bin/php

<?php
    function calc_arithmetic($var1,$var2){
        $sum = $var1 + $var2;
        $sub = $var1 - $var2;
        $mul = $var1 * $var2;
        $div = $var1 / $var2;

        return array(
            'sum'=>$sum,
            'sub'=>$sub,
            'mul'=>$mul,
            'div'=>$div
        );
    }

    $a = 20;
    $b = 3;
    $result = calc_arithmetic($a, $b);

    echo "Sum of $a and $b is {$result['sum']}\n";
    echo "Subtraction of $a and $b is {$result['sub']}\n";
    echo "Multiplication of $a and $b is {$result['mul']}\n";
    echo "Division of $a and $b is {$result['div']}\n";
?>

 

Output

$./function_return_array_demo.php 

Sum of 20 and 3 is 23
Subtraction of 20 and 3 is 17
Multiplication of 20 and 3 is 60
Division of 20 and 3 is 6.6666666666667

 

Returning an object from function

Example

function calc_arithmetic($var1,$var2){
    $sum = $var1 + $var2;
    $sub = $var1 - $var2;
    $mul = $var1 * $var2;
    $div = $var1 / $var2;

    return new Arithmetic($sum, $sub, $mul,$div);
}

 

function_return_object_demo.php

#!/usr/bin/php

<?php

    class Arithmetic{
        public $sum;
        public $sub;
        public $mul;
        public $div;

        public function __construct($sum, $sub, $mul, $div){
            $this->sum = $sum;
            $this->sub = $sub;
            $this->mul = $mul;
            $this->div = $div;
        }
    }

    function calc_arithmetic($var1,$var2){
        $sum = $var1 + $var2;
        $sub = $var1 - $var2;
        $mul = $var1 * $var2;
        $div = $var1 / $var2;

        return new Arithmetic($sum, $sub, $mul,$div);
    }

    $a = 20;
    $b = 3;
    $result = calc_arithmetic($a, $b);

    echo "Sum of $a and $b is {$result->sum}\n";
    echo "Subtraction of $a and $b is {$result->sub}\n";
    echo "Multiplication of $a and $b is {$result->mul}\n";
    echo "Division of $a and $b is {$result->div}\n";
?>

 

Output

$./function_return_object_demo.php 

Sum of 20 and 3 is 23
Subtraction of 20 and 3 is 17
Multiplication of 20 and 3 is 60
Division of 20 and 3 is 6.6666666666667

 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment