Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP return(value); vs return value;

Tags:

Is there any difference between return($var); and return $var; other then wrapping it in parentheses?

like image 846
Josh K Avatar asked May 27 '10 14:05

Josh K


People also ask

What is return value in PHP?

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.

Can you return two values in PHP?

A function can not return multiple values, but similar results can be obtained by returning an array.

How can get return value of function in PHP?

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.

How can I return two arrays in PHP?

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.


1 Answers

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).

like image 146
Mark Rushakoff Avatar answered Oct 12 '22 20:10

Mark Rushakoff