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?
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.
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.
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.
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.
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'];
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With