Is there any difference between return($var);
and return $var;
other then wrapping it in parentheses?
Definition and Usage. The return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running.
A function can not return multiple values, but similar results can be obtained by returning an array.
php function testMe() { try { $returnText = 'John King Rocks'; return $returnText; } catch (Exception $e) { return false; } } $str = testMe(); if ($str) { echo $str; } ?> Note, the return false; here is unreachable -- nothing in the try block will cause an exception.
Another option to consider is to use write parameters. Then, to call: $arr1 = array(); $arr2 = foobar($arr1); This won't be useful if you always need to return two arrays, but it can be used to always return one array and return the other only in certain cases.
Unless you are returning by reference, they mean the same thing. It is preferable to exclude the parentheses. From the docs:
Note: Note that since
return()
is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use
return ($a)
; then you're not returning a variable, but the result of the expression($a)
(which is, of course, the value of$a
).
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