0
function foo($a)
{
    $b = ...;
    $c = ...;
    return (both b and c);
}

and so I could get $b value to $first and $c value to $second

I know you can return more than 1 variable by return array($b,$c) but then it should be $var[0] and $var[1] and then I need to type $first = $var[0] and $second = $var[1] and so I'm creating more useless variables

So is it possible to do so without array?

4 Answers 4

2

Fundamentally, functions only have one return value. You could return a class with member variables first and second, or an associative array with keys "first" and "second", but you'll still only be returning a single object.*

Alternatively, you could references to $first and $second into your function:

function foo($a, &$b, &$c)
{
    $b = ...;
    $c = ...;
}

foo(42, $first, $second);

I'm not a big fan of this approach, though, because it's not immediately clear from the call-site that $first and $second are going to be modified.

* Note that if you return an array, you can always use the short-hand list($first,$second) = foo(42);.

Sign up to request clarification or add additional context in comments.

Comments

2

No, it can't.

But you can still return an array from function, but use "list" to accept the result for convenient:

list ($first, $second) = foo ($a);

Comments

1

No, you cannot to that. Function returns only one result.

What you can do, if possible in you case, is pass a variable by reference.

function foo($a, &$b, &$c){
 $b = ...;
 $c = ...;
}

The following will make changes to $b and $c visible outside of the function scope.

Comments

0

The only alternative to avoid returning an array is to return an object, or serialized data, but you don't "win" something from that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.