How to return more than one value or multi value in PHP
Some of PHP beginners (my friends) always ask me how to return two or more values from function. So , I thought, I may need to write the beginner tip at The Tech Space Blog. If your the advanced PHP programmer, you will say. So easy, It’s a piece of cake. For beginner, it would be a little difficult. So, let’s see how to write it.
For normal function ..
<?
function calc ( $a, $b)
{
$sum = $a+$b;
return $sum;
}
echo $calc(2,3);
?>
So, If you would like to return two or more value from that function, just only return as an array. Let’s see.
<?php
function calc($a,$b){
$sum = $a+$b;
$multiply = $a * $b;
$divided = $a/$b;
$modulus = $a%$b;
return array( 'sum'=>$sum, 'multiply'=>$multiply, 'divided'=> $divided, 'modulus'=>$modulus );
}
$data = calc(3,4);
echo 'Sum value: '.$data['sum'].'<br />';
echo 'Multiply value: '.$data['multiply'].'<br />';
echo 'Divided value: '.$data['divided'].'<br />';
echo 'Modulus value: '.$data['modulus'].'<br />';
?>
Enjoy !!!
- Tutorials
Filed Under
-
good job!! useful somewhat..
Made by Symmetric Web
Distributed by Smashing Magazine
Freelance Web Developer. Founder of The Tech Space. Follow me on Twitter.