Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning two values from a function [duplicate]

Is it possible to return two values when calling a function that would output the values?

For example, I have this:

<?php     function ids($uid = 0, $sid = '')     {         $uid = 1;         $sid = md5(time());          return $uid;         return $sid;     }      echo ids(); ?> 

Which will output 1. I want to chose what to ouput, e.g. ids($sid), but it will still output 1.

Is it even possible?

like image 804
MacMac Avatar asked Sep 28 '10 17:09

MacMac


People also ask

Can you return 2 values from a function?

You can't return two values. However, you can return a single value that is a struct that contains two values. Show activity on this post. You can return only one thing from a function.

How do I store two values returned from a function?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

Can I return 2 variables?

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.

Can a function return 2 values Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.


2 Answers

You can only return one value. But you can use an array that itself contains the other two values:

return array($uid, $sid); 

Then you access the values like:

$ids = ids(); echo $ids[0];  // uid echo $ids[1];  // sid 

You could also use an associative array:

return array('uid' => $uid, 'sid' => $sid); 

And accessing it:

$ids = ids(); echo $ids['uid']; echo $ids['sid']; 
like image 61
Gumbo Avatar answered Sep 18 '22 15:09

Gumbo


Return an array or an object if you need to return multiple values. For example:

function foo() {     return array(3, 'joe'); }  $data = foo(); $id = $data[0]; $username = $data[1];  // or: list($id, $username) = foo(); 
like image 32
Annika Backstrom Avatar answered Sep 20 '22 15:09

Annika Backstrom