PHP - exit or return which is better?

PhpTerminate

Php Problem Overview


I would like to know in the following case which is a better option:

In the PHP script, if the $fileSize variable is larger than 100, I stop the script;

Case I:

<?php
if ( $fileSize > 100 )
{
   $results['msg'] = 'fileSize is too big!';
   echo json_encode( $results );
   exit();
}

Case II:

<?php
if ( $fileSize > 100 )
{
   $results['msg'] = 'fileSize is too big!';
   exit( json_encode( $results ) );
}

Case III:

<?php
if ( $fileSize > 100 )
{
   $results['msg'] = 'fileSize is too big!';
   return( json_encode( $results ) );
}

Which of the three (3) options above is the best?

Php Solutions


Solution 1 - Php

Since you are using exit and return within the global scope (not inside a function), then the behavior is almost the same.

The difference in this case will appear if your file is called through include() or require(). exit will terminate the program, while return will take the control back to the calling script (where include or require was called).

Solution 2 - Php

I would tend to go with the return() method, so that other scripts can continue executing. That way, if you ever use another script to call this one, it can do error-handling to deal with the case where the file is too large, as opposed to always halting execution.

Solution 3 - Php

It depends...if your script is intended to do nothing else but output a message, and you don't want the script to do anything afterwards, exit() will work. Otherwise, use return.

Solution 4 - Php

Exit terminates the program like die(). manual

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionq0987View Question on Stackoverflow
Solution 1 - PhpAzizView Answer on Stackoverflow
Solution 2 - PhpJeffrey BlakeView Answer on Stackoverflow
Solution 3 - PhpCrayon ViolentView Answer on Stackoverflow
Solution 4 - PhpIznogoodView Answer on Stackoverflow