The difference and usage between return and exit break and contiue in PHP

  • 2020-05-16 06:34:38
  • OfStack

Let's start with the usage of the exit function.
Action: prints 1 message and terminates the current script.
If a paragraph of text contains multiple scripts that end, exit exits the current script.
For example, if an php text contains 1 code, the output is world.

< %
echo "hello";
exit;
? >
echo "world";
? >
Syntax: void means no return value.
void exit ([ string $status ] )
void exit ( int $status )
If status is a 1 string, this function prints status before the script exits.
If status is an integer, the integer is treated as an exit state. The exit state should be from 0 to 254, and the exit state 255 is reserved and disabled by PHP. State 0 is used to indicate a successful terminator.
The use of return language structures
Effect: terminates the execution of the function and returns a value from the function
break and continue are used in for, foreach, while, do.. while or switch.

break ends current for, foreach, while, do.. Implementation of while or switch structures.

break can accept an optional numeric parameter to decide how many loops to jump out of.

Code:
 
$arr = array ( ' one',  ' two',  ' three',  ' four',  ' stop',  ' five'); 
while (list (, $val) = each ($arr)) { 
if ($val ==  ' stop') { 
break; 
} 
echo "$val 
\n"; 
} 

$i = 0; 
while (++$i) { 
switch ($i) { 
case 5: 
echo "At 5 
\n"; 
break 1; 
case 10: 
echo "At 10; quitting 
\n"; 
break 2; 
default: 
break; 
} 
} 
?> 

continue is used in the loop structure to skip the rest of the code in this loop and start executing the next loop of the loop structure.

Note: note that in PHP the switch statement is considered a loop structure for continue purposes.

continue accepts an optional numeric parameter to decide how many loops to skip to the end of the loop.

Code:
 
<code> 
<?php 
while (list ($key, $value) = each ($arr)) { 
if (!($key % 2)) { // skip odd members 
continue; 
} 
do_something_odd ($value); 
} 
$i = 0; 
while ($i++ < 5) { 
echo "Outer<br>\n"; 
while (1) { 
echo "  Middle<br>\n"; 
while (1) { 
echo "  Inner<br>\n"; 
continue 3; 
} 
echo "This never gets output.<br>\n"; 
} 
echo "Neither does this.<br>\n"; 
} 
?></code> 

Note: this paragraph is from the Internet, the source is unknown

Related articles: