7
<?php

function testEnd($x) {
    if ( ctype_digit($x) ) {
        if ( $x == 24 ) {
            return true;
            exit;
        } else {
            return false;
                 exit;
        }
    } else {
        echo 'If its not a digit, you\'ll see me.';
        return false;
        exit;
    }
}

$a = '2';

if ( testEnd($a) ) {
    echo 'This is a digit';
} else {
    echo 'No digit found';
}
?>

Is exit needed along with return when using them inside a php function? In this case, if anything evaluated to false, i'd like to end there and exit.

3
  • 6
    Anything after return is unreachable, so useless Commented May 21, 2013 at 5:36
  • So I guess using only return true or false will do. If I only use exit the call function below does not perform as expected. Commented May 21, 2013 at 5:41
  • It's actually A Good Thing (TM) that it's after the return and thus useless .. or the code would simply perform "unexpectedly". Commented May 30, 2014 at 5:29

1 Answer 1

33

No it's not needed. When you return from a function then any code after that does not execute. if at all it did execute, your could would then stop dead there and not go back to calling function either. That exit should go

According to PHP Manual

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.

Whereas, exit, according to PHP Manual

Terminates execution of the script.

So if your exit was really executing, it would stop all the execution right there

EDIT

Just put up a small example to demonstrate what exit does. Let's say you have a function and you want to simply display its return value. Then try this

<?php

function test($i)
{
    if($i==5)
    {
        return "Five";
    }
    else
    {
        exit;
    }
}


echo "Start<br>";
echo "test(5) response:";
echo test(5);

echo "<br>test(4) response:";
echo test(4); 

/*No Code below this line will execute now. You wont see the following `End` message.  If you comment this line then you will see end message as well. That is because of the use of exit*/


echo "<br>End<br>";


?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.