,
Share this with your friends 
 

difference between die() Vs exit() in PHP

0 ratings Views 29 
Author: Modaser (Mr. Modaser )  View Profile |  View other solutions by this author

Question / Problem


What is the difference between exit() and die() functions in PHP?

Solution

Overview
We are all at starting phase of learning, PHP has a BIG question on what is the difference between die() and exit(). The excitement of preparing a code with both statements, searching for answers and getting to a result is heart whelming.
It’s a general tendency to use exit() for testing/stopping execution and die() for checking database connection/operations.
Let’s compare it both… A step by step explanation to die Vs exit
PHP Language Constructs comparison “exit” Vs “die”:
NOTE: Built-in Functions are slower compared to Language Constructs, Language Constructs does not need parenthesis.

Example 1:
Test exit:

<?php
for($count=0;$count<10;$count++) {
if($count==2)
exit(); // stops execution from this.
}
?>
Test die:

<?php
$dblink = mysql_connect('host.domain.com', 'mysql_user_one', 'mysql_password_for_user_one');
if (!$link) {
exit('Could not connect: ' . mysql_error()); // stops execution printing "Could not connect: MYSQL_ERROR"
}
echo 'Connected successfully';
mysql_close($link);
?>


The conclusion comes that both works SAME – there is no functional level differences with both.
If you check on php.net for die and exit definitions it’s mentioned:
exit — Output a message and terminate the current script
die — Equivalent to exit
But still there is a little or no difference – server need to read 4 characters for exit whereas server need to read 3 characters for die. For micro time difference die will execute faster then exit.
These are called “Aliases” – different name but same functional execution



Applies to

PHP

Rank It

Login to rank it

Report


Advertisement