i

PHP Tutorial

Returning Multiple Values From A Function

In programming languages like C or C++, we cannot return multiple values from a function. But php allows us to return multiple values from a function using arrays. So, with the help of arrays in php, you can return multiple values because the variables in php are flexible and no data type is required to declare the variables. 

Let us see an example of how we can return multiple values from a function in Php.

function calculation($num1, $num2)

{

           $add = $num1 + $num2;

           $sub = $num1 - $num2;

           $multi= $num1 *$num2;

           $div = $num1 / $num2;

           $result = array($add, $sub, $multi, $div);

       

           return $result;

$get_result = calculation (30,10);

echo “Addition: “ .$get_result[0].”
”;

echo “Subtraction: “ .$get_result[1].”
”;

echo “Multiplication: “ .$get_result[2].”
”;

echo “Division: “ .$get_result[3];

?>

 The output of the above code will be

 Addition : 40

Subtraction : 20

Multiplication : 300

Division : 3

So, we can return multiple values through a single function in PHP using arrays.