Tray2.se Logo

The return statement and how it's used

I've been covering some pretty advanced database related topics here, but today we are going to go back to the absolute fundamentals of programming and talk about one of the most powerful keywords in any programming language, the return. It tells your program that it should stop executing the function or method it is currently running and return anything that may or may not be between the return and the ending semicolon. This post uses php as the language of choice, but the principles are the same in most programming languages out there.

So what does that mean?

We will take a look at a few examples.

A return statement can return something, but it is not required, that means that both of these are valid syntax.

1return $somevariable;
2 
3return;

In our first case study we use a simple if statement that returns a value depending on the outcome of our comparison.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return 'Online';
5 } else {
6 return 'Offline';
7 }
8}

While this is a completely valid function, it has some unnecessary code that we can remove.

Remember this?

It tells your program that it should stop executing the function or method it is currently running.

That means that any code after the return will never get executed, and in our case, if the status is 1 then the code after the first return will not be executed. That means that we can remove the else statement and still have the same functionality, like so.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return 'Online';
5 }
6 
7 return 'Offline';
8}

That also means that you can't use multiple returns to return multiple values in the same function. This would simply not work, and it would just return the string Offline if the status isn't equal to one. The content of the variable status would never be returned, it's dead code.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return 'Online';
5 }
6 
7 return 'Offline';
8 return $status;
9}

This would return Offline everytime the status isn't equal to one. So if you need to return more than one value, you need to return a string with both values or an array.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return 'Online';
5 }
6 
7 return 'Offline' . $status;
8}

A string isn't always what you need, and then you can use an array to return multiple values.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return 'Online';
5 }
6 
7 return ['Offline', $status];
8}

However, in our case it's a bad practice since we then return two different data types. So doing something like this would be better.

1function getServerStatusDescription($status)
2{
3 if ($status == 1) {
4 return ['Online', $status];
5 }
6 
7 return ['Offline', $status];
8}

Now that we made sure that both cases returns the same datatype, we could take this on step further and use something called a ternary operator, this has nothing to do with the return statement at all, but it's still a valid option to have the same functionality in another (not necessarily better) way.

1function getServerStatusDescription($status)
2{
3 return [
4 $status == 1 ? 'Online' : 'Offline',
5 $status];
6}

This is called a ternary operator, and it's a shorthand way to write an if statement.

Just as a bonus, I will show you a better more readable way than the ternary operator, and this is only valid if you are using php 8.0 or higher, if you are running the 7.4 or older version of php, you really should consider upgrading, since they all have reached end-of-life, and are no longer supported.

1function getServerStatusDescription($status)
2{
3 return match($status) {
4 1 => ['Online', $status],
5 default => ['Offline', $status]
6 }
7}

In the example above we only use two options in the match statement since we used that number of options in our ternary example. There is nothing stopping you from adding more options to your match statement. As we learned, a return stops execution of a function and returns the value, so every line of code after a return statement inside the same code block is dead code, that is also true when the return is inside a loop.

1$names = [
2 'Carl',
3 'Ed',
4 'Michael',
5 'Michelle',
6 'Stephen'
7];
8 
9foreach ($names as $name) {
10 if (count(name) < 3 ) {
11 return 'Name is too short';
12 }
13 echo name . '<br>';
14}

The code above would stop running inside the second iteration, since Ed has less than three characters in his name, and we return if the number of characters is less than three.

There is a technique that I think is called Early Return, or at least something similar. Many times when you write an if statement you do something like this

1if (! isEmpty($someValue)) {
2 // do many lines of code
3}

While there is nothing wrong with doing that, it is still very easy to miss the ! aka not sign when you are reading the code.

There are two ways (at least) to improve this code.

the first way is to create a new function that is called isNotEmpty().

1if (isNotEmpty($someValue)) {
2 // do many lines of code
3}

The only objection I have to this is that you have an indented block of code inside your function, so how can we handle that?

With an early return of course.

1if (isEmpty($someValue)) return;
2 
3// do many lines of code

See, we don't need to negate, create another function, or indent our code, we just check if it is empty and return if it is.

I know what you are thinking, "but what about there being more than one online status?"

I think we all have written code like this more times than we would like to admit.

1if ($status == 1 ) {
2 return 'Online';
3} else if ($status == 2) {
4 return 'Handling Request';
5} else {
6 return 'Offline';
7}

We could of course use a switch statement here

1switch($status) {
2 case 1: return 'Online';
3 case 2: return 'Handling Request';
4 default : return 'Offline';
5}

They both do the same thing, and yes we don't need to use break when we use return.

No how can we avoid having multiple returns?

One way is only return once.

1function getServerStatusDescription($status)
2{
3 $serverStatus = 'Offline';
4 
5 if ($status == 1) {
6 $serverStatus = 'Online';
7 } else if ($status == 2) {
8 $serverStatus = 'Handling Request';
9 }
10 
11 return $serverStatus;
12}

That also means that we can rewrite our first example as well.

1function getServerStatusDescription($status)
2{
3 $serverStatus = 'Offline';
4 
5 if ($status == 1) {
6 $serverStatus = 'Online';
7 }
8 
9 return $serverStatus;
10}

Or if we are running an up to date php version we can use the match function, and remove the if statement completely, since it can handle a more or less infinite number of values.

As you can see, there are many ways to use return in your code. Use it wisely, and don't add too much logic into each function. It's much easier to understand a small five line function than a 50+ line one.

//Tray2

© 2024 Tray2.se. All rights reserved.

This site uses Torchlight for syntax highlighting.