Jump to content

Return multiple values: Difference between revisions

added php and python
(J)
(added php and python)
Line 24:
<lang j> 1 2+3 4
4 6</lang>
 
=={{header|PHP}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
 
<lang php>function addsub($x, $y) {
return array($x + $y, $x - $y);
}</lang>
 
You can use the <code>list()</code> construct to assign to multiple variables:
 
<lang php>list($sum, $difference) = addsub(33, 12);
echo "33 + 12 = $sum\n";
echo "33 - 12 = $difference\n";</lang>
 
=={{header|Pike}}==
Line 36 ⟶ 49:
[int z, int w] = addsub(5,4);
</lang>
 
=={{header|Python}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
 
<lang python>def addsub(x, y):
return x + y, x - y</lang>
 
(Note that parentheses are not necessary for a tuple literal in Python.)
 
You can assign to a comma-separated list of targets:
 
<lang python>sum, difference = addsub(33, 12)
print "33 + 12 = %s" % sum
print "33 - 12 = %s" % difference</lang>
 
=={{header|Ruby}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.