PHP - exit or return which is better?

q0987 picture q0987 · Aug 14, 2010 · Viewed 59.5k times · Source

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?

Answer

Aziz picture Aziz · Aug 14, 2010

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